Pytorch极简入门教程(三)—— 入门实例

import pandas as pd
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
data = pd.read_csv("dataset/Income1.csv")
print("data.info:\t", data.info)

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))

w = torch.randn(1, requires_grad=True)
b = torch.randn(1, requires_grad=True)

# 模型公式 w@input + b
learning_rate = 0.001
for epoch in range(500):
    for x, y in zip(X, Y):
        y_pred = torch.matmul(x, w) + b
        loss =(y-y_pred).pow(2).mean() # 均方误差
        if not w.grad is None: # 如果w.grad不为None,进入循环执行
            w.grad.data.zero_() # w.grad值置零
        if not b.grad is 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
print("w:\t", w)
print("b:\t", b)

plt.scatter(data.Education, data.Income)
# 因为w*X+b是变量,因此要取值就必须后面加.data
plt.plot(X.numpy(), (w*X+b).data.numpy(), c="r")
plt.show()
data.info:	 <bound method DataFrame.info of     Unnamed: 0  Education     Income
0            1  10.000000  26.658839
1            2  10.401338  27.306435
2            3  10.842809  22.132410
3            4  11.244147  21.169841
4            5  11.645485  15.192634
5            6  12.086957  26.398951
6            7  12.488294  17.435307
7            8  12.889632  25.507885
8            9  13.290970  36.884595
9           10  13.732441  39.666109
10          11  14.133779  34.396281
11          12  14.535117  41.497994
12          13  14.976589  44.981575
13          14  15.377926  47.039595
14          15  15.779264  48.252578
15          16  16.220736  57.034251
16          17  16.622074  51.490919
17          18  17.023411  61.336621
18          19  17.464883  57.581988
19          20  17.866221  68.553714
20          21  18.267559  64.310925
21          22  18.709030  68.959009
22          23  19.110368  74.614639
23          24  19.511706  71.867195
24          25  19.913043  76.098135
25          26  20.354515  75.775218
26          27  20.755853  72.486055
27          28  21.157191  77.355021
28          29  21.598662  72.118790
29          30  22.000000  80.260571>
w:	 tensor([4.2552], requires_grad=True)
b:	 tensor([-13.5366], requires_grad=True)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值