pytorch实现线性回归和多元回归的方法

  介绍

本篇内容介绍了“pytorch实现线性回归和多元回归的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

最近在学习pytorch,现在把学习的代码放在这里,下面是github链接

直接附上github代码

#,实现一个线性回归   #,所有的层结构和损失函数都来自于,torch.nn   #,torch.optim 是一个实现各种优化算法的包,调用的时候必须是需要优化的参数传入,这些参数都必须是变量   ,   x_train =, np.array ([(3.3)、(4.4)、(5.5)、(6.71), (6.93), (4.168), (9.779), (6.182), (7.59), (2.167), (7.042), (10.791), (5.313), (7.997), [3.1]], dtype=np.float32)   y_train =, np.array ([(1.7)、(2.76)、(2.09)、(3.19), (1.694), (1.573), (3.366), (2.596), (2.53), (1.221), (2.827), (3.465), (1.65), (2.904), [1.3]], dtype=np.float32)   ,   #,首先我们需要将数组转化成张量,因为pytorch处理的单元是张量   ,   时间=x_train  torch.from_numpy (x_train)   时间=y_train  torch.from_numpy (y_train)   ,   ,   #,def  a  simple 网络   ,   class  LinearRegression (nn.Module):   ,,,def  __init__(自我):   ,,,,,,,超级(LinearRegression,自我). __init__ ()   ,,,,,,,self.linear =, nn.Linear (1, 1),, #, input 以及output  is  2 _dimension   ,,,def 向前(自我,,x):   ,,,,,,,out =, self.linear (x)   ,,,,,,,return    ,   ,   if  torch.cuda.is_available ():   ,,,model =, LinearRegression () .cuda ()   ,,,# model =, model.cuda ()   其他:   ,,,model =, LinearRegression ()   ,,,# model =, model.cuda ()   ,   #,定义loss  function 和optimize 函数   时间=criterion  nn.MSELoss(),,, #,均方误差作为优化函数   时间=optimizer  torch.optim.SGD (model.parameters (), lr=1 e - 3)   num_epochs =30000   for  epoch 拷贝范围(num_epochs):   ,,,if  torch.cuda.is_available ():   ,,,,,,,inputs =,变量(x_train) .cuda ()   ,,,,,,,outputs =,变量(y_train) .cuda ()   ,,,:   ,,,,,,,inputs =,变量(x_train)   ,,,,,,,outputs =,变量(y_train)   ,   ,,,#,前进   ,,,out =,模型(输入)   ,,,loss =,则(输出),   ,   ,,,#向后制定   ,,,optimizer.zero_grad(),, #,每次做反向传播之前都要进行归零梯度。不然梯度会累加在一起,造成不收敛的结果   ,,,loss.backward ()   ,,,optimizer.step ()   ,   ,,,if  (epoch  + 1) % 20==0:   ,,,,,,,印刷(& # 39;时代({}/{}),失:,{:.6f} & # 39; .format(时代+ 1,num_epochs loss.data))   ,   ,   model.eval(),, #,将模型变成测试模式   时间=predict 模型(变量(x_train) .cuda ())   .numpy predict =, predict.data.cpu () ()   y_train.numpy plt.plot (x_train.numpy () () & # 39; ro # 39;, label =, & # 39; original 数据# 39;)   label  plt.plot (x_train.numpy(),预测,=,& # 39;Fitting 行# 39;)   plt.show ()

结果如图所示:

 pytorch实现线性回归和多元回归的方法

多元回归:

#, _ * _encoding=utf-8_ * _   #,pytorch 里面最基本的操作对象是张量,pytorch 的张量可以和numpy的ndarray相互转化。   #,实现一个线性回归   #,所有的层结构和损失函数都来自于,torch.nn   #,torch.optim 是一个实现各种优化算法的包,调用的时候必须是需要优化的参数传入,这些参数都必须是变量   ,   ,   #,实现,y =, b  +, w1  * x  +, w2  * x * * 2, + w3 * x * * 3   import 操作系统   os.environ [& # 39; CUDA_DEVICE_ORDER& # 39;]=癙CI_BUS_ID"   os.environ [& # 39; CUDA_VISIBLE_DEVICES& # 39;]=& # 39; 0 & # 39;   import 火炬   import  numpy  as  np   得到torch.autograd  import 变量   import  matplotlib.pyplot  as  plt   得到torch  import 神经网络   ,   ,   #,pre_processing   def  make_feature (x):   ,,,x =, x.unsqueeze (1),,, #, unsquenze 是为了添加维度1的,0表示第一维度,1表示第二维度,将张量大小由3变为(3,1)   ,,,return  torch.cat ([x  * *,小姐:for 小姐:拷贝范围(1,4)],,1)   ,   #,定义好真实的数据   ,   ,   def  f (x):   ,,,W_output =, torch.Tensor ([0.5,, 3,, 2.4]) .unsqueeze (1)   ,,,b_output =, torch.Tensor ([0.9])   ,,,return  x.mm (W_output) + b_output[0],, #,外积,矩阵乘法   ,   ,   #,批量处理数据   def  get_batch (batch_size =32):   ,   ,,,random =, torch.randn (batch_size)   ,,,x =, make_feature(随机)   ,,,y  f (x)=,   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

pytorch实现线性回归和多元回归的方法