【发布时间】:2020-08-09 23:07:16
【问题描述】:
我正在尝试使用 matplotlib 打印抛物面,这是简单线性回归的成本函数。问题是该函数看起来不像抛物面...... linear regression here fake paraboloid here 完美的直线是权重 2,偏差 0
def main():
#create database
n_samples = 40
x = np.linspace(0, 20, n_samples)
y = 2*x + 4*np.random.randn(n_samples)
#show
plt.scatter(x, y)
print_cost_func(x, y)
def cost_func(x: np.ndarray, y: np.ndarray, weight: int, bias: int) ->
float:
return np.sum((y - (weight*x + bias))**2) / (2*len(x))
def print_cost_func(x: np.ndarray, y: np.ndarray):
fig = plt.figure()
ax = fig.gca(projection='3d')
weight = np.arange(-50, 50, 0.25)
bias = np.arange(-50, 50, 0.25)
weight, bias = np.meshgrid(weight, bias)
Z = np.zeros((400, 400))
#i think the problem is here
for i in range(400):
for j in range(400):
Z[i][j] = cost_func(x, y, weight[i][j], bias[i][j])
# Plot the surface.
surf = ax.plot_surface(weight, bias, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Cost function')
plt.xlabel('Weight')
plt.ylabel('Bias')
plt.show()
【问题讨论】:
标签: python matplotlib machine-learning linear-regression