栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch 学习(一)simple linear model

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch 学习(一)simple linear model

1. 查看版本

torch.__version__

2. pandas 读取数据

import pandas as pd

data = pd.read_csv('./....csv')
data.head

data.info

3. 画散点图

import  matplotlib.pyplot as plt
plt.scatter(data.Education, data.Income)
plt.xlabel('Education')
plt.ylabel('Income')

4. 基本步骤:

        a. 数据预处理

        b. 设计模型 优化器 损失函数

        c. 训练

        d.  测试

记录样本和标签

data.Education.values


 

X = data.Education.values.reshape(-1,1)

Y = data.Income.values.reshape(-1,1)


 

X = torch.from_numpy(X)        #numpy --> tensor

Y = torch.from_numpy(Y)

X = X.type(torch.FloatTensor)

Y = Y.type(torch.FloatTensor)

 模型创建:

from torch import nn


class EIModel(nn.Module):
    def __init__(self):
        super(EIMdoel, self).__init__()
        self.linear = nn.Linear(in_features = 1 , out_features = 1)

    def forward(self, inputs):
        logits = self.linear(inputs)
        return logits

 损失函数 + 优化器

# 损失函数 均方误差
loss_fn = nn.MSELoss()

# 优化函数 随机梯度下降
# 模型参数 + 学习率
opt = torch.optim.SGD(model.parameters(), lr = 0.0001)

train 过程

for epoch in range(5000):
    for x,y in zip(X,Y):
        # 预测
        y_pred = model(x)
        # 计算损失
        loss = loss_fn(y_pred, y)
        # 梯度清零
        opt.zero_grad()
        # 反向传播
        loss.backward()
        # 更新参数
        opt.step()
        

list(model.parameters())                查看参数

model.linear.weight

查看拟合图像

plt.scatter(data.Education,  data.Income)

plt.xlabel('Education')
plt.ylabel('Income')

plt.plot(X.model(X).detach().numpy() , c = 'r')

 5. tensor 与 numpy 转换

tensor 2 numpy

t.numpy()

numpy 2 tenosr

torch.from_numpy()

参考b站 pytorch 教学

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号