一、线性回归
import torch
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import torch.optim as optim
in_features=1
out_features=1
x=torch.unsqueeze(torch.linspace(1,10,100),dim=1)
y=3.0*x+2+torch.rand(x.size())
plt.scatter(x.data.numpy(), y.data.numpy())
plt.show()
class MYNET(nn.Module):
def __init__(self):
super(MYNET,self).__init__()
self.L1=nn.Linear(1,1)
def forward(self,x):
x=self.L1(x)
return x
net=MYNET()
print(net)
lr=0.01
crition=nn.MSELoss()
opt=optim.SGD(net.parameters(),lr)
num_epochs=1000
for epoch in range(num_epochs):
y_out = net(x)
loss = crition(y_out, y)
opt.zero_grad()
loss.backward()
opt.step()
if (epoch + 1) % 20 == 0:
print('Epoch[{}/{}], loss:{:.6f}'.format(epoch + 1, num_epochs, loss.data))
net.eval()
predict=net(x)
predict=predict.data.numpy()
plt.plot(x.numpy(),y.numpy(),label='O