【PyTorch深度学习实践 P2】y=wx+b

模型y=wx+b的实现,及绘图

# FILE: 学习深度学习/Linear_Model
# USER: mcfly
# IDE: PyCharm
# CREATE TIME: 2024/9/2 8:29
# DESCRIPTION: 刘二大人 线性模型

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x_train = [1.0, 2.0, 3.0]
y_train = [3.0, 5.0, 7.0]

def forward( w, b, x):
    return w * x + b

def loss( y, y_head=0.0):
    return (y-y_head) * (y-y_head)

y_heads = []
mse_dict = {}

for w in np.arange(0.0,4.1,0.1):
    y_heads_i = []
    for b in np.arange( 0.0, 2.1, 0.1):
        loss_sum = 0.0
        for xi, yi in zip( x_train, y_train ):
            y_head_i = forward(w, b, xi)
            y_heads_i.append( y_head_i )
            loss_sum += loss( yi, y_head_i )
        loss_sum /= len(x_train)
        mse_dict[(w,b)] = loss_sum
        print( "w:{0}\nb:{1}\ny:{2}\nloss:{3}".format(w, b, y_heads_i, loss_sum))
    y_heads.append(y_heads_i)

local_min = min(mse_dict, key=lambda x:mse_dict[x])
print( "{} is the w that minimize the loss.".format(local_min))



x = [key[0] for key in mse_dict.keys()]
y = [key[1] for key in mse_dict.keys()]
z = list(mse_dict.values())

# 三维散点图
fig = plt.figure(num="Loss") 
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='b', marker='o')
# 画出坐标轴
ax.set_xlabel('w') 
ax.set_ylabel('b')
ax.set_zlabel('loss')

plt.show()
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值