模型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()