详解详解Pytorch 使用使用Pytorch拟合多项式拟合多项式(多项式回归多项式回归)
主要介绍了详解Pytorch 使用Pytorch拟合多项式(多项式回归),小编觉得挺不错的,现在分享给大家,也给大家
做个参考。一起跟随小编过来看看吧
使用Pytorch来编写神经网络具有很多优势,比起Tensorflow,我认为Pytorch更加简单,结构更加清晰。
希望通过实战几个Pytorch的例子,让大家熟悉Pytorch的使用方法,包括数据集创建,各种网络层结构的定义,以及前向传播
与权重更新方式。
比如这里给出
很显然,这里我们只需要假定
这里我们只需要设置一个合适尺寸的全连接网络,根据不断迭代,求出最接近的参数即可。
但是这里需要思考一个问题,使用全连接网络结构是毫无疑问的,但是我们的输入与输出格式是什么样的呢?
只将一个x作为输入合理吗?显然是不合理的,因为每一个神经元其实模拟的是wx+b的计算过程,无法模拟幂运算,所以显然
我们需要将x,x的平方,x的三次方,x的四次方组合成一个向量作为输入,假设有n个不同的x值,我们就可以将n个组合向量
合在一起组成输入矩阵。
这一步代码如下:
def make_features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1,4)] , 1)
我们需要生成一些随机数作为网络输入:
def get_batch(batch_size=32):
random = torch.randn(batch_size)
x = make_features(random)
'''Compute the actual results'''
y = f(x)
if torch.cuda.is_available():
return Variable(x).cuda(), Variable(y).cuda()
else:
return Variable(x), Variable(y)
其中的f(x)定义如下:
w_target = torch.FloatTensor([0.5,3,2.4]).unsqueeze(1)
b_target = torch.FloatTensor([0.9])
def f(x):
return x.mm(w_target)+b_target[0]
接下来定义模型:
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
if torch.cuda.is_available():
model = poly_model().cuda()
else:
model = poly_model()
接下来我们定义损失函数和优化器:
criterion = nn.MSELoss()
评论0