PyTorch 教程-实现深度神经网络
在了解了反向传播的过程之后,让我们开始看看如何使用PyTorch实现深度神经网络。实现深度神经网络的过程类似于感知器模型的实现。在实现过程中,我们需要执行以下步骤。
步骤1:
import torchimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasets
步骤2:
no_of_points=500datasets.make_blobs()
步骤3:
现在,我们将创建我们的数据集,并将数据点存储到变量x中,同时将值存储到变量y中,我们将使用标签作为稍后的参考。
x,y=datasets.make_blobs()
步骤4:
x, y = datasets.make_circles(n_samples=no_of_points, random_state=123, noise=0.1, factor=0.2)
👉点击领取:最全Python资料合集
步骤5:
plt.scatter(x[y==0,0],x[y==0,1])
步骤6:
plt.scatter(x[y==1,0],x[y==1,1])
单一线无法对上述数据集进行分类。要对这个数据集进行分类,将需要一个更深层次的神经网络。
def Scatter():plt.scatter(x[y==0,0],x[y==0,1])plt.scatter(x[y==1,0],x[y==1,1])
步骤7:
class Deep_neural_network(nn.Module):def __init__(self,input_size, h1, output_size):super().__init__()self.linear=nn.Linear(input_size, h1) # input layer connect with hidden layerself.linear1=nn.Linear(h1, output_size) # hidden layer connect with output layer
def forward(self,x):x=torch.sigmoid(self.linear(x)) # Return the prediction xx=torch.sigmoid(self.linear1(x)) # Prediction will go through the next layer.return x # Returning final outputs
xdata=torch.Tensor(x)ydata=torch.Tensor(y)
步骤8:
print(list(model.parameters()))
torch.manual_seed(2)
步骤9:
criterion=nn.BCELoss()
optimizer=torch.optim.Adam(model.parameters(),lr=0.01)
如果选择最小的学习率,它会导致非常缓慢地收敛到最小值,如果选择非常大的学习率可能会阻碍收敛。Adam优化算法最终计算每个参数的自适应学习率。
步骤10:
epochs=1000losses=[]For i in range (epochs):ypred=model.forward(x) #Prediction of yloss=criterion(ypred,y) #Find losslosses.append() # Add loss in listoptimizer.zero_grad() # Set the gradient to zeroloss.backward() #To compute derivativesoptimizer.step() # Update the parameters
热门推荐