【发布时间】:2021-03-07 22:49:20
【问题描述】:
我正在尝试在一个简单的训练数据集上实现成本函数,并在 3D 中可视化成本函数。
我的成本函数的形状不像它应该的那样。
这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.axes3d import Axes3D
import pandas as pd
from scipy.interpolate import griddata
def create_array(start, end, resolution):
return np.linspace(start, end, int((end - start)/resolution + 1))
def f(x,a,b):
x = np.array(x)
return a*x+b # or Theta_1 * x + Theta_0
def get_J(x, y, a, b):
x = np.array(x)
y = np.array(y)
# return 1/(2*len(y)) * sum(pow(f(x,a,b) - y, 2))
# Simple implementation
sum = 0
for i in range(0, len(x)):
sum+= (f(x[i],a,b) - y[i])**2
return 1/(2*len(y))*sum
# Training set
x = np.array([0,1,2,3])
y = np.array([0,1,2,3])
Theta_0 = create_array(-20, 10, 0.5)
Theta_1 = create_array(-20, 10, 0.5)
X,Y = np.meshgrid(Theta_0, Theta_1)
X=X.flatten()
Y=Y.flatten()
J = [get_J(x, y, X[i], Y[i]) for i in range(0,len(X))]
# simple set to verify 3D plotting is doing as expetected - OK
# X = [10, 0, -10,-20, 10, 0, -10,-20, 10, 0,-10, -20, 10, 0, -10,-20]
# Y = [-20, -20, -20, -20, -10, -10, -10, -10, 0, 0, 0, 0, 10, 10, 10, 10]
# J = [50, 25, 26, 60, 24, 10, 11, 26, 10, 0, 2, 11, 52, 26, 27, 63]
# Create the graphing elements
xyz = {'x': X, 'y': Y, 'z': J}
# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x'])))
# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')
fig = plt.figure(figsize =(14, 9))
ax = Axes3D(fig)
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=plt.get_cmap('coolwarm'),linewidth=0, antialiased=False)
plt.gca().invert_xaxis()
ax.set_xlabel('\u03B81', fontweight ='bold')
ax.set_ylabel('\u03B80', fontweight ='bold')
ax.set_zlabel('J (\u03B81, \u03B80)', fontweight ='bold')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
【问题讨论】:
-
参考图片从何而来?构建参考图像的方程式是什么?他们使用相同的数据吗?
-
@maij 参考图片来自教授这些原则的课程。没有迹象表明使用了哪个数据集,很可能数据集可能不同,因此不应坚持 J 值。不过形状应该是一样的。不幸的是,我找不到我的错误。
标签: python machine-learning linear-regression