本文代码参考廖星宇《深度学习入门之PyTorch》中的示例代码,手动复现而来,仅供个人使用,侵删。
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
#Define Model
class poly_model(nn.Module):
def __init__(self):
super(poly_model, self).__init__()
self.poly = nn.Linear(3, 1)
def forward(self, x):
out = self.poly(x)
return out
#Build features-> a matrix with columns [x,x^2,x^3]
def make_feature(x):
x= x.unsqueeze(1)
return torch.cat([x ** i for i in range(1,4)], 1)
#Approximated function
def f(x):
return x.mm(W_target) + b_target[0]
#Build a batch->(x,f(x)) pair
def get_batch(batch_size=32):
random = torch.randn(batch_size)
random = np.sort(random)
random = torch.Tensor(random)
x = make_feature(random)
y = f(x)
if torch.cuda.is_available(