手动构建线性回归(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()
相关推荐
大写的z先生4 分钟前
【深度学习 | 论文精读】Bi-GCN:社交媒体谣言检测的双向图卷积网络
深度学习·语言模型
AI-Ming5 分钟前
程序员转行学习AI大模型:位置编码
人工智能·神经网络·学习
AC赳赳老秦11 分钟前
OpenClaw关键词挖掘Agent配置(附SOP脚本,可直接复制使用)
java·大数据·开发语言·人工智能·python·pygame·openclaw
进击的野人11 分钟前
深入RAG:从理论到实践的 ETL 核心流程
人工智能·spring·agent
央链知播14 分钟前
以价值立品牌 以生态共成长 —— 明月三千里的高质量发展实践
大数据·人工智能
leo__52015 分钟前
MATLAB高斯背景建模与目标提取(人体检测)
开发语言·人工智能·matlab
深藏功yu名18 分钟前
Day24(进阶篇):向量数据库 Chroma_FAISS 深度攻坚 —— 索引优化、性能调优与生产级落地
数据库·人工智能·python·ai·agent·faiss·chroma
AI扑社23 分钟前
AI时代下品牌建设的革命:从流量争夺到AI赋能的价值深耕
大数据·人工智能·geo·ai搜索
guoji778824 分钟前
chatGPT5.4镜像如何重塑复杂问题解决范式:从对话助手到智能体执行者
大数据·人工智能·gpt·chatgpt
zzh9407730 分钟前
2026年国外四大主流镜像大模型深度对比:chatGPT、Gemini、Claude、Grok
人工智能·chatgpt