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):