手动构建线性回归(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()
相关推荐
AI人工智能+11 小时前
行驶证识别技术融合计算机视觉与自然语言处理,实现对模糊、倾斜、反光等复杂场景下行驶证的高精度结构化数据提取
人工智能·深度学习·自然语言处理·ocr·行驶证识别
weixin_7503302314 小时前
AI获客工具选型:从技术架构看中小企业效率提升方案
大数据·人工智能·架构·ai获客
mpp00715 小时前
36氪《2026 中国 AI Agent 行业发展报告》:当 Agent 进入「交付」主战场
大数据·人工智能
吃饱了得干活17 小时前
Agent 的决策与规划:ReAct、Plan-and-Execute、Reflexion 与 Tree of Thoughts
人工智能·llm·agent
阿明617 小时前
小白入门机器学习基础【AI】
人工智能·机器学习
java资料站17 小时前
十一、评估测试
开发语言·人工智能·python
东方佑17 小时前
从《事件发生与智能》的框架看中国古代命理学
人工智能·深度学习·语言模型·自然语言处理·架构
天远API18 小时前
零信任架构实战:基于天远运营商三要素简版V即时版查询构建自动化司乘安全绑定网关
人工智能·安全·架构·自动化
Henry-SAP18 小时前
SAP PP核心引擎计划策略业务解析
人工智能·云原生·sap·erp
DP DPharness18 小时前
拆开 dsh-knowledge 的检索链路,看 RRF 融合与锚点续读
人工智能·dpharness