【深度学习】复习温故而知新1

数据集ref:https://raw.githubusercontent.com/justinge/pic-go-for-xbotgo/master/Income1.csv

复制代码
X = torch.from_numpy(data.Education.values.reshape(-1,1).astype(np.float32))
Y = torch.from_numpy(data.Income.values.reshape(-1,1).astype(np.float32))

y_pred = model(x) # 预测
loss = loss_fn(y, y_pred) # 计算损失
opt.zero_grad() # 梯度清零
loss.backward() # 反向传播
opt.step() # 下一次

总的来说

python 复制代码
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("/home/data_for_ai_justin/01learn/dataset/Income1.csv")
X = torch.from_numpy(data.Education.values.reshape(-1,1).astype(np.float32))
Y = torch.from_numpy(data.Income.values.reshape(-1,1).astype(np.float32))
loss_fn = nn.MSELoss()
int_features, out_features = 1, 1
model = nn.Linear(int_features,out_features)
opt = torch.optim.SGD(
    model.parameters(),
    lr=0.0001
)
for i in range(5000):
    for x,y in zip(X,Y):
        y_pred = model(x)
        loss = loss_fn(y, y_pred)
        opt.zero_grad()
        loss.backward()
        opt.step()

plt.scatter(data.Education, data.Income)
plt.plot(X.numpy(), model(X).data.numpy(),c='r')
plt.savefig("1.jpg")

分解写法

python 复制代码
df = pd.read_csv("/home/data_for_ai_justin/01learn/dataset/Income1.csv")
X=torch.from_numpy(df.Education.values.reshape(-1,1).astype(np.float32))
Y=torch.from_numpy(df.Income.values.reshape(-1,1).astype(np.float32))
w = torch.randn(1,requires_grad=True)
b = torch.zeros(1,requires_grad=True)
learning_rate = 0.001
for i in range(5000):
    for x,y in zip(X,Y):
        y_pred = torch.matmul(x,w) + b
        loss=(y-y_pred).pow(2).mean()
        if w.grad is not None:
            w.grad.data.zero_()
        if b.grad is not None:
            b.grad.data.zero_()
        loss.backward()
        with torch.no_grad():
            w.data -= w.grad.data * learning_rate
            b.data -= b.grad.data * learning_rate
plt.scatter(df.Education, df.Income)
plt.xlabel = "x"
plt.ylabel = "y"
plt.plot(X.numpy(), (torch.matmul(X,w) + b).data.numpy(),c='r')
plt.show()
        
相关推荐
love530love27 分钟前
Windows 11 下 Z-Image-Turbo 完整部署与 Flash Attention 2.8.3 本地编译复盘
人工智能·windows·python·aigc·flash-attn·z-image·cuda加速
雪下的新火32 分钟前
AI工具-Hyper3D
人工智能·aigc·blender·ai工具·笔记分享
Das11 小时前
【机器学习】01_模型选择与评估
人工智能·算法·机器学习
墨染天姬1 小时前
【AI】AI时代,模组厂商如何建立自己的AI护城河?
人工智能
aigcapi1 小时前
[深度观察] RAG 架构重塑流量分发:2025 年 GEO 优化技术路径与头部服务商选型指南
大数据·人工智能·架构
字节跳动开源1 小时前
Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁
前端·人工智能·客户端
+wacyltd大模型备案算法备案2 小时前
大模型备案怎么做?2025年企业大模型备案全流程与材料清单详解
人工智能·大模型备案·算法备案·大模型上线登记
吾在学习路2 小时前
故事型总结:Swin Transformer 是如何打破 Vision Transformer 壁垒的?
人工智能·深度学习·transformer
sandwu3 小时前
AI自动化测试(一)
人工智能·agent·playwright·ai自动化测试·midscene