标签:mat optimize show 二维 优化器 function def att ram
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
# 把一维变二维
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())
x, y= Variable(x),Variable(y)
# plt.scatter(x.data.numpy(),y.data.numpy())
# plt.show()
继承两次
然后定义每层的结点数
# 定义神经网络
class Net(torch.nn.Module):
def __init__(self,n_feature,n_hidden,n_output,):
super(Net,self).__init__()
self.hidden = torch.nn.Linear(n_feature,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
net = Net(1,10,1)
# 打印这个神经网络
print(net)
# 定义优化器和损失函数
optimizer = torch.optim.SGD(net.parameters(),lr=0.5)
loss_func = torch.nn.MSELoss()
Net(
(hidden): Linear(in_features=1, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=1, bias=True)
)
for i in range(100):
prediction = net(x)
loss = loss_func(prediction,y)
# 优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i % 20 == 0:
# 打印误差
print(loss)
tensor(0.1574, grad_fn=<MseLossBackward>)
tensor(0.0912, grad_fn=<MseLossBackward>)
tensor(0.0687, grad_fn=<MseLossBackward>)
tensor(0.0310, grad_fn=<MseLossBackward>)
tensor(0.0188, grad_fn=<MseLossBackward>)
先变torch,在变Variable
在预测使用net(x)
x1 = torch.FloatTensor([1])
x1 = torch.unsqueeze(x1,dim=1)
x1 = Variable(x1)
net(x1)
tensor([[0.9546]], grad_fn=<AddmmBackward>)
标签:mat optimize show 二维 优化器 function def att ram
原文地址:https://www.cnblogs.com/liu247/p/11145597.html