python - matplotlib上线性回归一个变量的成本函数
问题描述
我正在尝试使用 matplotlib 打印抛物面,这是简单线性回归的成本函数。问题是函数看起来不是抛物面...... 这里的线性回归 假抛物面这里 完美的直线是权重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()
解决方案
推荐阅读
- html - Jsoup 获取产品描述
- c++ - cppreference的编码风格在哪里定义的?
- c# - c#在while循环中使用JavaScriptSerializer序列化器并返回客户端到Json.Parse。收到错误
- powershell - 如何允许用户使用 PowerShell 只检查一个复选框列表?
- sql - 使用一个 UPDATE 命令将列中的某些值更改为 SQL 中的某些其他值
- node.js - 快速会话 GET 与 POST 请求
- php - 优化返回行数很大的MySQL查询
- javascript - express-flash() 给 Toastr 时识别数据类型
- javascript - js循环问题
- multithreading - 使用 pthread 库的 c 语言中的线程问题