PyTorch学习日志_20201031_线性模型

日期:2020.10.31
主题:PyTorch入门
内容:

  • 学习如何构建线性模型解决问题。

问题:学习时长 x 与考试成绩 y 的关系?

学习时长 x考试成绩 y
12
24
36
4

思路:
在这里插入图片描述

具体代码如下 ↓

import numpy as np
import matplotlib.pyplot as plt
# Import necessary library to draw the graph

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# Prepare the train set

def forward(x):
    return x * w
# Define the model

def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2
# Define the loss function

w_list = []     # Save the weights w
mse_list = []   # Save the cost values of each w

for w in np.arange(0.0, 4.1, 0.1):
# Compute cost value at [0.0, 0.1, 0.2, ..., 4.0]
    print('w = ', w)
    l_sum = 0
    for x_val, y_val in zip(x_data, y_data): # get [(x1, y1), ...]
        y_pred_val = forward(x_val)
        loss_val = loss(x_val, y_val)
        l_sum += loss_val
        print('\t', x_val, y_val, y_pred_val, loss_val)
        # For each sample in train set, the loss function values were computed.
    MSE = l_sum / 3
    print('MSE = ', MSE)
    w_list.append(w)
    mse_list.append(MSE)
    
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
# Draw the graph



结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值