Pytorch学习笔记(五)--多层神经网络
前请提要
Pytorch学习笔记(一)--Tensor和Variable
Pytorch学习笔记(二)--autograd and dynamic-graph
Pytorch学习笔记(三)--linear regression andgradient descend(线性回归和梯度下降)
Pytorch学习笔记(四)--Logistic 回归模型
一.多层神经网络
之前学习的线性模型和logistic模型可以看作是单层神经网络,在logistic模型是 y = sigmoid(wx + b),sigmoid可以看作是激活函数,在神经网络中必须有激活函数.如果不使用激活函数 y = wn…(w1x) => y = w*n 本质上就变成了一层神经网络.
神经网络的原型来源与人类的神经网络,即从上个神经元等传来的信号经过突触传入的下个神经元,通过激活这个神经元,让信号传递到下个神经元.神经网络就是上一层网络的输入经过激活函数来输出传递到下一层.
以下是常见的激活函数:
- sigmoid 激活函数
σ(x)=1/(1+e^x)
- tanh 激活函数
tanh(x)=2σ(2x)−1
- ReLU 激活函数
ReLU(x)=max(0,x)
一般一个一层的神经网络的公式就是 y=max(0,wx+b) ,一个两层的神经网络就是 y=w2 max(0,w1x+b1)+b2 ,非常简单,但是却很有效,使用这个激活函数能够加快梯度下降法的收敛速度,同时对比与其他的激活函数,这个激活函数计算更加简单.
神经网络就是很多个神经元堆在一起形成一层神经网络,那么多个层堆叠在一起就是深层神经网络.每层神经元的个数和神经网络的层数都是可以调节的参数,会对网络产生大的影响
例子:对比一层与多层网络
画出样本点
import torch import numpy as np from torch import nn from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt def plot_decision_boundary(model, x, y): # Set min and max values and give it some padding x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1 y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1 h = 0.01 # Generate a grid of points with distance h between them xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole grid Z = model(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.ylabel('x2') plt.xlabel('x1') plt.scatter(x[:, 0], x[:, 1], c=y.reshape(-1), s=40, cmap=plt.cm.Spectral) np.random.seed(1) m = 400 # 样本数量 N = int(m/2) # 每一类的点的个数 D = 2 # 维度 x = np.zeros((m, D)) y = np.zeros((m, 1), dtype='uint8') # label 向量,0 表示红色,1 表示蓝色 a = 4 for j in range(2): ix = range(N*j,N*(j+1)) t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius x[ix] = np.c_[r*np.sin(t), r*np.cos(t)] y[ix] = j plt.scatter(x[:, 0], x[:, 1], c=y.reshape(-1), s=40, cmap=plt.cm.Spectral) # plt.show()
采用logistic模型
x = torch.from_numpy(x).float() y = torch.from_numpy(y).float() w = nn.Parameter(torch.randn(2, 1)) b = nn.Parameter(torch.zeros(1)) optimizer = torch.optim.SGD([w, b], 1e-1) def logistic_regression(x): return torch.mm(x, w) + b criterion = nn.BCEWithLogitsLoss() for e in range(100): out = logistic_regression(Variable(x)) loss = criterion(out, Variable(y)) optimizer.zero_grad() loss.backward() optimizer.step() if (e + 1) % 20 == 0: print('epoch: {}, loss: {}'.format(e+1, loss.item())) def plot_logistic(x): x = Variable(torch.from_numpy(x).float()) out = F.sigmoid(logistic_regression(x)) out = (out > 0.5) * 1 return out.data.numpy() plot_decision_boundary(lambda x: plot_logistic(x), x.numpy(), y.numpy()) plt.title('logistic regression') plt.show()
使用两层神经网络
x = torch.from_numpy(x).float() y = torch.from_numpy(y).float() # 定义两层神经网络的参数 w1 = nn.Parameter(torch.randn(2, 4) * 0.01) # 隐藏层神经元个数 2 b1 = nn.Parameter(torch.zeros(4)) w2 = nn.Parameter(torch.randn(4, 1) * 0.01) b2 = nn.Parameter(torch.zeros(1)) # 定义模型 def two_network(x): x1 = torch.mm(x, w1) + b1 x1 = F.tanh(x1) # 使用 PyTorch 自带的 tanh 激活函数 x2 = torch.mm(x1, w2) + b2 return x2 optimizer = torch.optim.SGD([w1, w2, b1, b2], 1.) criterion = nn.BCEWithLogitsLoss() # 我们训练 10000 次 for e in range(100): out = two_network(Variable(x)) loss = criterion(out, Variable(y)) optimizer.zero_grad() loss.backward() optimizer.step() if (e + 1) % 1000 == 0: print('epoch: {}, loss: {}'.format(e+1, loss.item())) def plot_network(x): x = Variable(torch.from_numpy(x).float()) x1 = torch.mm(x, w1) + b1 x1 = F.tanh(x1) x2 = torch.mm(x1, w2) + b2 out = F.sigmoid(x2) out = (out > 0.5) * 1 return out.data.numpy() plot_decision_boundary(lambda x: plot_network(x), x.numpy(), y.numpy()) plt.title('2 layer network train 100') plt.show()
epoch: 1000, loss: 0.29067105054855347
epoch: 2000, loss: 0.2533509135246277
epoch: 3000, loss: 0.2366824746131897
epoch: 4000, loss: 0.229623943567276
epoch: 5000, loss: 0.2252798229455948
epoch: 6000, loss: 0.2221824824810028
epoch: 7000, loss: 0.21980053186416626
epoch: 8000, loss: 0.21788650751113892
epoch: 9000, loss: 0.21631284058094025
epoch: 10000, loss: 0.2150006741285324
二.Sequential 和 Module
未完待续......
- MLP(多层神经网络)介绍
- 学习笔记CB009:人工神经网络模型、手写数字识别、多层卷积网络、word2vec
- TensorFlow实战4:实现简单的多层神经网络案例
- MLP(多层神经网络)介绍
- 小白学Tensorflow之多层神经网络
- ufldl学习笔记与编程作业:Multi-Layer Neural Network(多层神经网络+识别手写体编程)
- 深度学习与多层神经网络的区别
- 神经网络学习笔记(九):多层感知机(上)
- 多层神经网络Multi-layer networks
- Halcon学习 多层神经网络
- 【UFLDL】多层神经网络
- 多层神经网络与反向传播算法
- TF之BN:BN算法对多层中的每层神经网络加快学习QuadraticFunction_InputData+Histogram+BN的Error_curve
- 机器学习小试(2)使用多层神经网络进行分类实验
- 用Tensorflow实现多层神经网络
- Tensorflow--多层神经网络
- 神经网络之多层感知机MLP的实现(Python+TensorFlow)
- 多层神经网络中的正则化代价函数解析
- 【吴恩达课后编程作业】01 - 神经网络和深度学习 - 第四周 - PA1&2 - 一步步搭建多层神经网络以及应用
- Tensorflow实战学习(十一)【多层神经网络】