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 教学

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值