【发布时间】:2021-10-17 02:44:55
【问题描述】:
我正在尝试渲染成本函数的 3D 图。给定一个数据集和两个不同的参数(theta0 和 theta1),我想渲染一个我们在经典文献中都看到的碗状图形。我的假设函数只是一个简单的h(x) = theta_0 + theta_1 * x。但是,我的成本函数呈现如下:
得到这个情节可以吗?如果是的话,我们怎么能画出这样一个“碗”呢?
import matplotlib.pyplot as plt
import numpy as np
training_set = np.array([
[20, 400],
[30, 460],
[10, 300],
[50, 780],
[15, 350],
[60, 800],
[19, 360],
[31, 410],
[5, 50],
[46, 650],
[37, 400],
[39, 900]])
cost_factor = (1.0 / (len(training_set) * 2))
hypothesis = lambda theta0, theta1, x: theta0 + theta1 * x
cost = lambda theta0, theta1: cost_factor * sum(map(
lambda entry: (hypothesis(theta0, theta1, entry[0]) - entry[1]) ** 2, training_set))
theta1 = np.arange(0, 10, 1)
theta2 = np.arange(0, 10, 1)
X, Y = np.meshgrid(theta1, theta1)
Z = cost(X, Y)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
ax.set_xlabel(r'$\theta_0$')
ax.set_ylabel(r'$\theta_1$')
ax.set_zlabel(r'$J(\theta_0, \theta_1)$')
ax.set_title('Cost function')
plt.show()
【问题讨论】:
标签: python numpy matplotlib math data-science