请写出实现线性回归的代价损失函数的3d图的代码
时间: 2023-12-03 08:45:27 浏览: 21
以下是使用Python和matplotlib库实现线性回归代价损失函数的3D图的代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.zeros_like(X)
# 定义线性回归代价损失函数
def cost_function(x, y, theta):
m = len(y)
J = np.sum((x.dot(theta) - y) ** 2) / (2 * m)
return J
# 计算代价损失函数
for i in range(len(x)):
for j in range(len(y)):
Z[i][j] = cost_function(x=np.array([1, x[i]]), y=np.array([y[j]]), theta=np.array([0, 0]))
# 绘制3D图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('theta0')
ax.set_ylabel('theta1')
ax.set_zlabel('J')
plt.show()
```
运行以上代码,即可得到线性回归代价损失函数的3D图。