模型如图所示:8维到6维到4维到1维
数据集为自己照着课件里的数据输入的,其中每个数据以\t隔开
import numpy as np
import torch
import matplotlib.pyplot as plt
xy = np.loadtxt('data1.txt', delimiter = '\t', dtype = np.float32)#因为我的txt中数据之间是用\t隔开,所以delimiter = '\t'
x_data = torch.from_numpy(xy[:,:-1])#逗号前为行,都需要;逗号后为列除了最后一列都需要
y_data = torch.from_numpy(xy[:,[-1]])#逗号前为行,都需要;逗号后为列只需要最后一列
loss_list = []
Epoch_list = []
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.Sigmoid()#也可以使用其他激活函数,如torch.nn.ReLU()
def forward(self, x):
x = self.activate(self.linear1(x))
x = self.activate(self.linear2(x))
x = self.activate(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(size_average = True)#返回loss均值
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
loss_list.append(loss.item())
Epoch_list.append(epoch)
optimizer.zero_grad()#权重梯度清零
loss.backward()#反馈
optimizer.step()#权重更新
plt.plot(Epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
结果:
打印x_data和y_data的数据如下:
tensor([[-0.2900, 0.4900, 0.1800, -0.2900, 0.0000, 0.0000, -0.5300, -0.0300], [-0.8800, -0.1500, 0.0800, -0.4100, 0.0000, -0.2100, -0.7700, -0.6700], [-0.0600, 0.8400, 0.0500, 0.0000, 0.0000, -0.3100, -0.4900, -0.6300], [-0.8800, -0.1100, 0.0800, -0.5400, -0.7800, -0.1600, -0.9200, 0.0000], [ 0.0000, 0.3800, -0.3400, -0.2900, -0.6000, 0.2800, 0.8900, -0.6000], [-0.4100, 0.1700, 0.2100, 0.0000, 0.0000, -0.2400, -0.8900, -0.7000], [-0.6500, -0.2200, -0.1800, -0.3500, -0.7900, -0.0800, -0.8500, -0.8300], [ 0.1800, 0.1600, 0.0000, 0.0000, 0.0000, 0.0500, -0.9500, -0.7300], [-0.7600, 0.9800, 0.1500, -0.0900, 0.2800, -0.0900, -0.9300, 0.0700], [-0.0600, 0.2600, 0.5700, 0.0000, 0.0000, 0.0000, -0.8700, 0.1000]]) tensor([[0.], [1.], [0.], [1.], [0.], [1.], [0.], [1.], [0.], [0.]])