上代码:
#拟合y=0.9+0.5*x+3*x^2
# y = b + w1 *x + w2 *x**2
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
from torch import nn
# pre_processing
def make_feature(x):
x = x.unsqueeze(1) # unsquenze 是为了添加维度1的,0表示第一维度,1表示第二维度,将tensor大小由3变为(3,1)
return torch.cat([x ** i for i in range(1, 3)], 1)
W_output = torch.Tensor([0.5,3]).unsqueeze(1)
b_output = torch.Tensor([0.9])
# 定义好真实的数据
def f(x):
return x.mm(W_output) + b_output[0] # mm实现矩阵乘法
# 批量处理数据
def get_batch(batch_size=18):
random = torch.randn(batch_size)
x = make_feature(random)
y = f(x)
if torch.cuda.is_available():
return Variable(x).cuda(), Variable(y).cuda()
else:
return Variable(x), Variable(y)
# def model
class poly_model(nn.Module):
def __init__(self):
super(poly_model, self).__init__()
self.poly = nn.Linear(2, 1) # 输入2维,输出1维
def forward(self, input):
output = self.poly(input)
retur