手动构建线性回归(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()
相关推荐
新智元7 分钟前
AI 教父 Hinton 末日警告!你必须失业,AI 万亿泡沫豪赌才能「赢」
人工智能·openai
新智元12 分钟前
CUDA 再见了!寒武纪亮出软件全家桶
人工智能·openai
oe101918 分钟前
好文与笔记分享 A Survey of Context Engineering for Large Language Models(下)
人工智能·笔记·语言模型·agent
有为少年19 分钟前
告别乱码:OpenCV 中文路径(Unicode)读写的解决方案
人工智能·opencv·计算机视觉
清风与日月22 分钟前
halcon分类器使用标准流程
深度学习·目标检测·计算机视觉
西西阿西哥25 分钟前
【随便聊聊】和ChatGPT聊聊潜空间
深度学习·chatgpt
FreeCode1 小时前
LangChain1.0智能体开发:模型使用
人工智能·langchain·agent
张较瘦_1 小时前
[论文阅读] AI+ | 从 “刚性科层” 到 “智能协同”:一文读懂 AI 应对国家安全风险的核心逻辑
论文阅读·人工智能
anscos1 小时前
庭田科技亮相成都复材盛会,以仿真技术赋能产业革新
大数据·人工智能·科技
阿里云大数据AI技术1 小时前
PAI Physical AI Notebook 详解 1:基于 Isaac 仿真的操作动作数据扩增与模仿学习
人工智能