手动构建线性回归(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()
相关推荐
K***72848 小时前
开源模型应用落地-工具使用篇-Spring AI-Function Call(八)
人工智能·spring·开源
Chat_zhanggong3458 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
霍格沃兹软件测试开发8 小时前
Playwright MCP浏览器自动化指南:让AI精准理解你的命令
运维·人工智能·自动化
强化学习与机器人控制仿真8 小时前
RSL-RL:开源人形机器人强化学习控制研究库
开发语言·人工智能·stm32·神经网络·机器人·强化学习·模仿学习
网易智企9 小时前
智能玩具新纪元:一个AI能力底座开启创新“加速度”
人工智能·microsoft
咚咚王者9 小时前
人工智能之数据分析 numpy:第十二章 数据持久化
人工智能·数据分析·numpy
沛沛老爹9 小时前
AI应用入门之LangChain中SerpAPI、LLM-Math等Tools的集成方法实践
人工智能·langchain·llm·ai入门·serpapi
roman_日积跬步-终至千里10 小时前
【强化学习基础(5)】策略搜索与学徒学习:从专家行为中学习加速学习过程
人工智能
杭州泽沃电子科技有限公司11 小时前
在线监测:为医药精细化工奠定安全、合规与质量基石
运维·人工智能·物联网·安全·智能监测
GIS数据转换器11 小时前
GIS+大模型助力安全风险精细化管理
大数据·网络·人工智能·安全·无人机