java做线性模型代码_如何用pytorch中的SGD成功训练一个简单的线性回归模型?

本文介绍了作者在使用PyTorch的SGD优化器训练一个简单的多项式线性回归模型时遇到的问题。尽管模型参数有所变化,但损失函数并未收敛到预期的零误差。作者提供了代码示例并分享了解决问题的关键:将`y_pred = model(batch_xs)`更改为`y_pred = model(batch_xs).view(-1)`,这使得损失函数计算正确。
摘要由CSDN通过智能技术生成

我试图用SGD在pytorch中训练一个简单的多项式线性回归模型 . 我写了一些自包含(我认为是非常简单的代码),然而,由于某种原因,我的模型没有按照我的想法进行训练 .

我从正弦曲线中采样了5个点,并尝试用4度多项式拟合它 . 这是一个凸问题,所以只要我们有足够的迭代和足够小的步长,GD或SGD应该找到零列车误差的解决方案 . 尺寸 . 出于某种原因,我的模型不能很好地训练(即使它似乎正在改变模型的参数 . 任何人都知道为什么?这是代码(我尝试使其自包含和最小):

import numpy as np

from sklearn.preprocessing import PolynomialFeatures

import torch

from torch.autograd import Variable

from maps import NamedDict

from plotting_utils import *

def index_batch(X,batch_indices,dtype):

'''

returns the batch indexed/sliced batch

'''

if len(X.shape) == 1: # i.e. dimension (M,) just a vector

batch_xs = torch.FloatTensor(X[batch_indices]).type(dtype)

else:

batch_xs = torch.FloatTensor(X[batch_indices,:]).type(dtype)

return batch_xs

def get_batch2(X,Y,M,dtype):

'''

get batch for pytorch model

'''

# TODO fix and make it nicer, there is pytorch forum question

X,Y = X.data.numpy(), Y.data.numpy()

N = len(Y)

valid_indices = np.array( range(N) )

batch_indices = np.random.choice(valid_indices,size=M,replace=False)

batch_xs = index_batch(X,batch_indices,dtype)

batch_ys = index_batch(Y,batch_indices,dtype)

return Variable(batch_xs, requires_grad=False), Variable(batch_ys, requires_grad=False)

def get_sequential_lifted_mdl(nb_monomials,D_out, bias=False):

return torch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值