pytorch实现BP,处理多维数据输入

学习b站刘二大人视频所写
视频传送门

import torch
import matplotlib.pyplot as plt
import numpy as np

xy = np.loadtxt('000.txt', delimiter=' ', dtype=np.float32)
x_data = torch.from_numpy(xy[:, :-1])  # 取前九列
y_data = torch.from_numpy(xy[:, [-1]]) # 取最后一列


class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = torch.nn.Linear(9, 6)
        # linear(x1,x2)的两个参数分别表示输入输出的维度(矩阵的列数)
        #这里的9与数据集的列数一至
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()
		#激活函数用于实现非线性化
    def forward(self, x1):
        x1 = self.sigmoid(self.linear1(x1))
        x1 = self.sigmoid(self.linear2(x1))
        x1 = self.sigmoid(self.linear3(x1))
        return x1


model = Model()

# construct loss and optimizer
criterion = torch.nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.02)  
# model.parameters()自动完成参数的初始化操作
loss_sum = []
# training cycle forward, backward, update
for epoch in range(100):
    y_pred = model(x_data)  # forward 算预测值
    loss = criterion(y_pred, y_data)  # forward: 算损失值
    print(epoch, loss.item())
    loss_sum.append(loss)
    optimizer.zero_grad()  # 清除上一轮的梯度,防止累积
    loss.backward()  # backward: autograd,自动计算梯度,反向传播
    optimizer.step()  # update 参数,即更新w和b的值


x = range(100)
y = loss_sum
plt.plot(x, y)
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.grid() # 生成网格
plt.show()

pytorch实现BP,处理多维数据输入_第1张图片

你可能感兴趣的:(python及AI,神经网络,python,机器学习,深度学习)