7-处理多维特征的输入

行是样本,列是feather特征:

激活函数:

损失函数和优化器:

写代码步骤:

np.loadtxt()方法:

numpy.loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None)

点击查看代码
import torch
import numpy as np

xy = np.loadtxt('diabetes.csv.gz', 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(8,6)
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()  #不同于之前的sigmoid,前面py文件中用的sigmoid是torch.nn.functional中的,是一个方法,这里用的是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(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(100):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print('epoch:', epoch, 'loss:', loss.item())

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
posted @ 2024-08-14 16:07  不是孩子了  阅读(7)  评论(0编辑  收藏  举报