# 【PyTorch基础教程7】多维特征input

# -*- 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

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)

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())

梯度清零后反向传播

loss.backward()

更新权重

optimizer.step()

plt.plot(range(10), losslst)

plt.ylabel('Loss')

plt.xlabel('epoch')

plt.show()

• 博文量
10
• 访问量
1946