文章目录
线性回归
代码过程
训练过程:
- 准备数据集
- 设计模型(用来计算 y ^ \hat y y^)
- 构造损失函数和优化器(API)
- 训练周期(前馈、反馈、更新)
准备数据
这里的输入输出数据均表示为3×1的,也就是维度均为1
# 行表示实例数量,列表示维度feature
import torch
x_data=torch.Tensor([[1.0],[2.0],[3.0]])
y_data=torch.Tensor([[2.0],[4.0],[6.0]])
设计模型
模型继承Module类,并且必须要实现 init 和 forward 两个方法,其中
self.linear=torch.nn.Linear(1,1)
表示实例化Linear类,这个类是可调用的,其__call__
函数调用了 forward 方法
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel,self).__init__()
# weight 和 bias 1 1
self.linear=torch.nn.Linear(1,1)
def forward(self,x):
# callable
y_pred=self.linear(x)
return y_pred
# callable
model=LinearModel()
pytorch中的linear类是在某一个数据上应用线性转换,其公式表达为 y = x w T + b y=xw^T+b y=xwT+b
class torch.nn.Linear(in_features,out_features,bias=True) :其中in_features和out_features分别表示输入和输出的数据的维度(列的数量),bias表示偏置,默认是true,该类有两个参数
- weight:可学习参数,值从均匀分布 U ( − k , k ) U(-\sqrt k,\sqrt k) U(−k,k)中获取,其中 k = 1 i n _ f e a t u r e s k=\frac{1}{in\_features} k=in_features1
- bias:shape和输出的维度一样,也是从分布 U ( − k , k ) U(-\sqrt k,\sqrt k) U(−k,k