import torch
import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.modules
import torch.nn.functional as fun
# 第一种建立网络的方法
class Net(torch.nn.Module):
def __init__(self,n_features,n_hidden,n_outs):
super(Net,self).__init__()
self.hidden = torch.nn.Linear(n_features,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_outs)
def forward(self,x):
# relu是激励函数
x = fun.relu(self.hidden(x))
x = self.predict(x)
return x
net = Net(1,10,1)
# 第二种建立网络的方法
net = torch.nn.Sequential(
torch.nn.Linear(1,10),
torch.nn.ReLU(),
torch.nn.Linear(10,1)
)
optimizer = torch.optim.SGD(net.parameters(),lr = 1e-2)
loss_func = torch.nn.MSEloss()
for i in range(1000):
prediction = net(x)
# 计算损失
loss = loss_func(prediction, y)
print(i, loss)
optimizer.zero_grad()
# 反向传播
loss.backward()
# 更新参数
optimizer.step()
plt.scatter(x.numpy(), y.numpy())
plt.plot(x.numpy(), prediction.data.numpy(), 'r-')
plt.show()
今日pytorch
最新推荐文章于 2024-09-06 16:38:41 发布