【Pytorch深度学习实践】第7讲 处理多维特征的输入

什么是矩阵:
空间转换,从N维映射到M维空间的线性变换
神经网络:非线性空间变换

# Multiple_Dimension_Input
# 处理多维数据输入
import numpy as np
import torch

xy = np.loadtxt('data/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()

    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(100):
    # 前馈
    y_pred = model(x_data)
    # 损失
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())

    # 梯度清零
    optimizer.zero_grad()
    # 反向传播
    loss.backward()
    # 更新优化参数
    optimizer.step()


你可能感兴趣的:(PyTorch深度学习实践)