import numpy as np
import torch
import matplotlib.pyplot as plt
# 载入数据集
# xy是载入的数组,touch.from_numpy把载入的数组转化为张量
xy = np.loadtxt('diabetes.csv', delimiter=',', dtype=np.float32) # 一般用32位浮点数
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(8,6) #八位空间的向量映射到6维(空间维度变换)
self.linear2 = torch.nn.Linear(6,4)
self.linear3 = torch.nn.Linear(4,1)
# self.linear4 = torch.nn.Linear(2,1)
self.sigmoid = torch.nn.Sigmoid()
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 = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(),lr=0.1)
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch%10 == 0:
# y_pred_label = torch.where(y_pred >= 0.5, torch.tensor([1.0]), torch.tensor(0.0))
# acc = torch.eq(y_pred_label,y_data).sum().item()/y_data.size(0)
#print("loss=", loss.item(), "acc=", acc)
print("loss=", loss.item())
07 处理多维特征输入
最新推荐文章于 2024-09-11 11:22:05 发布