手动构建线性回归(PyTorch)

python 复制代码
import torch
from sklearn.datasets import make_regression
import matplotlib.pyplot as plt
import random
#1.构建数据
#构建数据集
def create_dataset():
    x,y,coef=make_regression(n_samples=100,
                             n_features=1,
                             random_state=0,
                             noise=10,
                             coef=True,
                             bias=14.5)
    #将构建数据转换为张量类型
    x=torch.tensor(x)
    y=torch.tensor(y)
    return x,y

#构建数据加载器
def data_loader(x,y, batch_size):
    #计算下样本的数量
    data_len = len(y)
    #构建数据索引
    data_index=list(range(data_len))

    random.shuffle(data_index)
    #计算总的batch数量
    batch_number=data_len//batch_size
    for idx in range(batch_number):
        start=idx+batch_size
        end=start+batch_size
        batch_train_x=x[start:end]
        batch_train_y=y[start:end]
        yield batch_train_x,batch_train_y

def test01():
    x,y=create_dataset()
    plt.scatter(x,y)
    plt.show()

    for x,y in data_loader(x,y,batch_size=10):
        print(y)
#2.假设函数、损失函数、优化方法
#损失函数:平均损失
#优化方法:梯度下降
#假设函数
w=torch.tensor(0.1,requires_grad=True,dtype=torch.float64)
b=torch.tensor(0.1,requires_grad=True,dtype=torch.float64)



def linear_regression(x):
    return w*x+b

#损失函数
def square_loss(y_pred,y_true):
    return torch.square(y_pred - y_true)

#优化方法
def sqd(lr=1e-2):
    #除以16是使用的是批次样本的平均梯度
    w.data=w.data-lr*w.grad.data/16
    b.data=b.data-lr*b.grad.data/16
    

if __name__ == '__main__':
    test01()
相关推荐
武子康12 分钟前
Vercel Cache Reason:相同 MISS,怎样决定下一步查什么
人工智能·后端·agent
4SAPI13 分钟前
内容生成与文本润色场景下的大模型 API 聚合网关选型指南
人工智能·gateway·php
诸神缄默不语14 分钟前
小春学习日刊 2026年第7期:2026.10.24
人工智能
qq_4523962319 分钟前
第二篇:《安装、配置与 psql 高效使用》
人工智能
方方洛25 分钟前
ray教程-11-可观测性与调试
人工智能·分布式·机器学习
我是李工啊28 分钟前
PRD 总和代码对不上?让 AI 从代码生成状态图和权限矩阵
人工智能·产品经理
ComputerInBook30 分钟前
泛函分析概观
人工智能·算法·机器学习·泛函分析
burg_xun41 分钟前
【生命科学 Agent】推理平台(二)
人工智能·程序人生·系统架构
IT_陈寒1 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
lanxiaoqing021 小时前
演讲训练的第一步:先敢说,再会说
人工智能·学习·学习方法·口才