import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x**2 + 0.2*torch.rand(x.shape)
#output to see the figure
# plt.scatter(x,y)
# plt.show()
class Net(torch.nn.Module):
def __init__(self,n_features,n_hidden,n_output):
super(Net,self).__init__() #继承
self.hidden = torch.nn.Linear(n_features, n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = self.hidden(x)
x = F.relu(x)
x = self.predict(x)
return x
net = Net(1,10,1)
optimizer = torch.optim.SGD(net.parameters(),lr=0.2)
loss_func = torch.nn.MSELoss() #MSE : mean square error
for t in range(100):
#forward
prediction = net.forward(x)
#get loss
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t%5 == 0:
x_test = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
prediction = net.forward(x_test)
# prediction = net(x)
plt.cla()
plt.scatter(x_test.data.numpy(), y.data.numpy())
plt.plot(x_test.data.numpy(), prediction.data.numpy())
# plt.show()
plt.pause(0.1)
pytorch linear regression
最新推荐文章于 2024-09-19 22:53:03 发布