# 简单的多层感知机（二维输入，一维输出，一层隐藏层）

import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pylab as plt
#1.构建数据集
x=torch.tensor([[1.0,1.0],#注意是二维的
[2.0,2.0],
[3.0,3.0]])
y=torch.tensor([[3.0],
[5.0],
[7.0]])
plt.scatter(x[:,0],y)
plt.show()
#搭建神经网络
class LinearNet(torch.nn.Module):
def __init__(self,num_input,num_hidden,num_output):
super(LinearNet, self).__init__()
self.hidden=torch.nn.Linear(num_input,num_hidden)
self.predict=torch.nn.Linear(num_hidden,num_output)

def forward(self,x):
x=F.relu(self.hidden(x))
x=self.predict(x)
return x

#对象具象化
net=LinearNet(2,4,1)

#定义优化器和损失函数
optimizer=torch.optim.SGD(net.parameters(),lr=0.5)
loss_func=torch.nn.MSELoss()

#定义epoch 和 进行训练
for epoch in range(1,101):
prediction=net(x) #向前传播 得到预期值
loss=loss_func(prediction,y) #向前传播 算出损失量 构建计算图

print(epoch,loss)

loss.backward() #向后传播 算出梯度 释放计算图
optimizer.step()# 梯度下降

print(net.hidden.weight.detach())  #net.hidden.weight.item()
print(net.hidden.bias.detach())
print(net.predict.weight.detach())
print(net.predict.weight.detach())
x_test=torch.tensor([[4.0,4.0]])
print(net(x_test).data.item())


03-01 8825

10-17 1865
07-27 1033
06-23 6万+
01-26 326
07-28 730
06-05 1711
02-16 803
06-01 2万+
02-14 221
05-17 2091