python复现吴恩达机器学习线性回归作业中的三维图

刚开始学习ML和python,复现一个三维图也用了相当几个小时,在已获取到的一维下降序列和三维图需要输入的二维数据之间迷惑了一下 ,最后还是参考作业的思路使用嵌套循环获取二维数据。等到熟悉python之后或许有更优雅的方法来实现。
参考文章(表面图):https://www.cnblogs.com/xingshansi/p/6777945.html

作业中应实现的效果

在这里插入图片描述

代码

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
# ax = fig.gca(projection='3d')
ax = fig.add_subplot(projection='3d')
# 创建0.01步长的θ1和θ2数组,初始化一个z矩阵.
_theta0_s = np.arange(-5, 5, 0.01)
_theta1_s = np.arange(-5, 5, 0.01)
Z = np.zeros((1000,1000))
for index0 in range(len(_theta0_s)):
    t1=_theta0_s[index0]
    for index1 in range(len(_theta1_s)):
        t2=_theta1_s[index1]
        v_t=[t1,t2]
        Z[index0,index1]=lr_cost(v_t, X, y)
_theta0_s, _theta1_s = np.meshgrid(_theta0_s, _theta1_s)
# 看下数据维度.
print(_theta0_s.shape)
print(_theta1_s.shape)
print(Z.shape)
surf = ax.plot_surface(_theta0_s, _theta1_s, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
# ax.set_zlim(-1.01, 1.01)这句限制z轴范围
# ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
# fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

其中lr_cost(v_t, X, y)计算代价函数,来自大神的作业,在这里也贴上

def lr_cost(theta, X, y):
#     """
#     X: R(m*n), m 样本数, n 特征数
#     y: R(m)
#     theta : R(n), 线性回归的参数
#     """
    m = X.shape[0]#m为样本数

    inner = X @ theta - y  # R(m*1)X @ theta等价于X.dot(theta)

    # 1*m @ m*1 = 1*1 in matrix multiplication
    # but you know numpy didn't do transpose in 1d array, so here is just a
    # vector inner product to itselves
    square_sum = inner.T @ inner
    cost = square_sum / (2 * m)

    return cost

最终实现的效果:
在这里插入图片描述
修改样本范围可获得作业同款三维图。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值