python
复制代码
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 假设函数为 y = 2x + 1
x_data = [1.0, 2.0, 3.0]
y_data = [3.0, 5.0, 7.0]
# 定义模型
def forward(x):
return x * w + b
# 定义损失函数
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
# mes 平方误差
mes_list = []
# w, b权重
W = np.arange(0.0, 3.1, 0.1)
B = np.arange(0.0, 3.1, 0.1)
# 画3D曲面图时,传入的参数必须是数据值或二维矩阵
# 利用meshgrid函数讲w,b两列数据转化为二维矩阵
[w, b] = np.meshgrid(W, B)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val) # 预测值
print(y_pred_val)
loss_val = loss(x_val, y_val) # 计算损失
l_sum += loss_val
# 绘3D图展示
fig = plt.figure()
ax =fig.add_axes(Axes3D(fig))
ax.plot_surface(w, b, l_sum/3)
plt.show()