一、课堂代码
我把激活函数换成了ReLU和sigmoid,大家可以自行尝试~
数据集的话下载方式在b站视频的评论区,和ppt一起;下载后和程序放在同个目录下就行
import torch
import numpy as np
import matplotlib.pyplot as plt
'''np.loadtxt函数用于从文本文件加载数据,
'diabetes.csv.gz'是你要加载的文件名,
.gz扩展名表示文件被gzip压缩,
delimiter=','表示CSV文件中数据以逗号分隔,
dtype=np.float32表示数据应该以32位浮点数的形式加载'''
xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:,:-1]) #切片操作,选择所有行,选择1到倒数第二列
y_data = torch.from_numpy(xy[:, [-1]]) #所有行,最后一列,加[]是为了把向量转变成矩阵,x_data,y_data在计算时都得是矩阵
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear1 = torch.nn.Linear(8, 6)
self.linear2 = torch.nn.Linear(6, 4)
self.linear3 = torch.nn.Linear(4, 1)
self.activate = torch.nn.ReLU()
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.activate(self.linear1(x))
x = self.activate(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
epoch_list = []
l_list = []
for epoch in range(100):
#forward
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
epoch_list.append(epoch)
l_list.append(loss.item())
print(epoch, loss.item())
#backward
optimizer.zero_grad()
loss.backward()
#update
optimizer.step()
plt.plot(epoch_list, l_list)
plt.grid(True)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.savefig('多维特征输入.png')
plt.show()
结果: