分类: Python/Ruby
2021-10-19 17:27:16
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 10:18:24 2021
@author: 86493
"""
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# 这里的type不用double,特斯拉GPU才double
xy = np.loadtxt('diabetes.csv',
delimiter = ' ',
dtype = np.float32)
# 最后一列不要
x_data = torch.from_numpy(xy[: , : -1])
# [-1]则拿出来的是一个矩阵,去了中括号则拿出向量
y_data = torch.from_numpy(xy[:, [-1]])
losslst = []
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear1 = nn.Linear(9, 6)
self.linear2 = nn.Linear(6, 4)
self.linear3 = nn.Linear(4, 1)
# 外汇跟单gendan5.com上次logistic是调用nn.functional的Sigmoid
self.sigmoid = nn.Sigmoid()
# 这个也是继承Module,没有参数,比上次写法不容易出错
def forward(self, x):
x = self.sigmoid(self.linear1(x))
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x
model = Model()
# 使用交叉熵作损失函数
criterion = nn.BCELoss(size_average = False)
optimizer = torch.optim.SGD(model.parameters(),
lr = 0.01)
# 训练,下面没有用mini-batch,后面讲dataloader再说
for epoch in range(10):
y_predict = model(x_data)
loss = criterion(y_predict, y_data)
# 打印loss对象会自动调用__str__
print(epoch, loss.item())
losslst.append(loss.item())
# 梯度清零后反向传播
optimizer.zero_grad()
loss.backward()
# 更新权重
optimizer.step()
# 画图
plt.plot(range(10), losslst)
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.show()