线性回归实现

这篇博客介绍了如何在PyTorch中实现线性回归模型。首先,定义了线性方程并生成带噪声的数据。接着,定义了一个数据迭代器以批量处理数据。然后,通过定义损失函数、梯度下降优化器以及训练过程,逐步更新模型参数。最终,模型参数接近真实值,展示了梯度下降在求解线性回归问题中的应用。
摘要由CSDN通过智能技术生成
import torch
from matplotlib import pyplot as plt
import numpy as np
# y=5*x1+3*x2+4
true_w = torch.tensor([5,3],dtype=torch.float32)
true_b = torch.tensor([4])

# 生成数据就
def generate_data(w,b,num_examples):
    x = torch.normal(0,1,(num_examples,len(w)))
    # If the first argument is 2-dimensional and the second
    # argument is 1-dimensional, the matrix-vector product is returned.
    y = torch.matmul(x, true_w)+b+torch.normal(0,0.01,[num_examples])# noise
    return x,y.reshape((-1,1)) # from 1000->1000*1


features,labels = generate_data(true_w,true_b,1000)

# 读取数据集
def data_iter(batch_size,features,labels):
    num_examples = len(labels)
    indices = np.arange(num_examples)
    np.random.shuffle(indices)
    for i in range(0,num_examples,batch_size):
        batch_indices  =indices[i:min(num_examples,i+batch_size)]
        #只给行索引就行
        yield features[batch_indices],labels[batch_indices]

def loss(y_yita,y):
    # If both tensors are 1-dimensional,
    # the dot product (scalar) is returned.
    #
    c = 0.5*torch.matmul(y_yita-y.reshape(y_yita.shape),y_yita-y.reshape(y_yita.shape))
    return c


# Returns a new Tensor, detached from the current graph.
# plt.scatter(features[:, 0].detach().numpy(), labels.detach().numpy(),1)
# plt.show()
# python 传参传的是地址也使得梯度下降更加方便
def sgd(params,lr,batch_size):
    with torch.no_grad():# 没有的话会有a leaf Variable that requires grad
        # has been used in an in-place operation
        # 如果不用backward会节省时间
        for param in params:
            # 梯度反方向是函数下降最快的方向
            # 损失函数本身就需要batch_size来衡量损失
            param-=lr*param.grad/batch_size
            param.grad.zero_()

train_w = torch.normal(0,1,true_w.shape,requires_grad=True)
train_b = torch.normal(0,1,true_b.shape,requires_grad=True)
def train(lr,features,labels,batch_size,train_w,train_b):
    for X,y in data_iter(batch_size,features,labels):
        y_yita = torch.matmul(X,train_w)+train_b
        y_yita.reshape((-1,1))
        l = loss(y_yita,y)
        l.backward()
        sgd([train_w,train_b],lr,batch_size)
    return train_w,train_b

train_w,train_b=train(0.03,features,labels,5,train_w,train_b)
print(train_w,train_b)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值