刚开始学习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
最终实现的效果:
修改样本范围可获得作业同款三维图。