Pytorch入门1

Pytorch神经网络基础

Tensor

tensor称为张量,Torch能够将torch中的tensor放到GPU中加速运算。

import torch

import numpy as np

 

data = [1, 2, 3, 4]

tensor1 = torch.LongTensor(data) #list---> tensor

np_data1 = tensor1.numpy()    #tensor ---> array

 

np_data2 = np.array(data)   #list ---> array

tensor2 = torch.from_numpy(np_data1) #array---> tensor

Variable

神经网络用到的数据类型是Variable,所以Variable相当于一个篮子,要用Variable把tensor装起来才行。

import torch

from torch.autograd import Variable

 

tensor = torch.FloatTensor([[1,2], [3, 4]])

x = Variable(tensor, requires_grad=True)    #tensor要转变成Variable的形式才能加入到神经网络中

v_out = torch.mean(x*x)

 

v_out.backward()

print(x.grad)

Activation Function

激励函数有很多中,最常用的几种为relu,sigmoid,tanh,softplus,softmax。卷积神经网络中常用relu,循环神经网络中常用tanh、relu。softmax不能直接画出来,关于概率用于分类。

import numpy as np

import torch

import torch.nn.functional as F #神经网络中的激励函数都在这

from torch.autograd import Variable #torch中运算的基本神经元是Variable

 

x = torch.linspace(-5,5,200)    #x data(tensor),从-5到5之间200个数据,(200,1)

#print(x)

x = Variable(x)

x_np = x.data.numpy()   #转换成numpy,画图的时候用

 

#  relu, sigmoid, tanh, softplus

y_relu = F.relu(x).data.numpy()

y_sigmoid = F.sigmoid(x).data.numpy()

y_tanh = F.tanh(x).data.numpy()

y_softplus = F.softplus(x).data.numpy()

#softmax比较特殊,不能直接显示,不过它是关于概率的,用于分类

建造神经网络

1、  数据集及数据预处理

2、  搭建合适的神经网络

3、  训练

net = Net()       #建造神经网络

opt = torch.optim.XXX(net.parameters(), lr=X)  #选择合适的优化器,如随机梯度下降SGD

loss_func = torch.nn.XXX()       #选择合适的损失函数,如MSELoss

for epoch in range(EPOCH):

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值