Skip to main content
 首页 » 编程设计

python之使用经过训练的权重绘制 3d 超平面

2024年10月24日8jyk

我不确定这对回归任务到底有多大用处,但如果能看到我的算法对训练集的学习情况如何,那就太好了。

我发现绘制 2D 问题非常简单,但在 3D 中绘制时遇到问题。

import numpy as np 
import itertools 
import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 
 
 
def gradient_descent(x, y, w, lr, m, iter): 
    xTrans = x.transpose() 
    for i in range(iter): 
        prediction = np.dot(x, w) 
        loss = prediction - y 
        cost = np.sum(loss ** 2) / m 
 
        print("Iteration %d | Cost: %f" % (i + 1, cost)) 
 
        gradient = np.dot(xTrans, loss) / m     # avg gradient 
 
        w -= lr * gradient   # update the weight vector 
 
    return w 
 
it = np.ones(shape=(100, 3))    # it[:,2] will be set of bias values 
x = np.arange(1, 200, 20) 
d = np.random.uniform(-100, 100, 100) 
 
m, n = np.shape(it) 
 
# initialise weights to 0 
w = np.zeros(n) 
 
# produce a 100x2 containing every combination of x 
indx = 0 
for a, b in itertools.product(x, x): 
    it[indx][0] = a 
    it[indx][1] = b 
    indx += 1 
 
# function with uniform distribution 
y = .4*it[:,0] + 1.4*it[:,1] + d 
 
iter = 1500             # number of iterations 
lr = 0.00001            # learning rate / alpha 
 
trained_w = gradient_descent(it, y, w, lr, m, iter) 
result = trained_w[0] * it[:,0] + trained_w[1] * it[:,1] + trained_w[2]  # linear plot of our predicted function 
print("Final weights: %f | %f | %f" % (trained_w[0], trained_w[1], trained_w[2])) 
 
# scatter of data set + trained function hyperplane 
plt3d = plt.figure().gca(projection='3d') 
plt3d.hold(True) 
plt3d.scatter(it[:,0], it[:,1], y) 
x_surf, y_surf = np.meshgrid(it[:,0], it[:,1]) 
plt3d.plot_surface(x_surf, y_surf, result) 
 
plt.show() 

我的情节结果有点奇怪:

请您参考如下方法:

问题是您在绘图中混淆了维度。

您首先从 (x,x) 构建网格。如果我理解正确的话,你可以用 meshgrid 做同样的事情:

x = np.arange(1, 200, 20) 
N = x.size 
a,b = np.meshrid(x,x) 
it = np.array([b.ravel(),a.ravel(),np.ones(N)]) 

然后您对随机输入数据进行训练,并获得函数 result,它是一个长度为 N^2 的数组,每个坐标包含一个点在 it 中配对(形状为 (N^2,3))。最后,您从它生成一个新网格,并尝试使用这些坐标和结果绘制一个表面。

所以你要传递两个坐标,x_surf 和 y_surf 形状 (N^2,N^2) 和一个表面值形状(N^2,) 到plot_surf 的结果。这样做的唯一原因是 matplotlib 可能使用数组广播来解释输入,并将较小数量的值复制到较大数量的坐标。

所以你有两个选择。使用输入网格绘制表面,或者如果出于某种原因需要使用不同的网格(例如,选择更大/更小的域来绘制表面),请使用双线性插值/外推法重新计算表面。好的,这是一种非常奇特的说法

result = trained_w[0] * x_surf + trained_w[1] * y_surf + trained_w[2] 
# instead of 
# result = trained_w[0] * it[:,0] + trained_w[1] * it[:,1] + trained_w[2] 

如果您坚持使用原始网格,则必须将其np.reshape 恢复为(N,N) 形状以制作plot_surface 快乐;如果采用上述方法,您的 result 将已经具有适合绘图的正确形状。使用前一种方法:

plt3d = plt.figure().gca(projection='3d') 
plt3d.hold(True) 
plt3d.scatter(it[:,0], it[:,1], y) 
plt3d.plot_surface(np.reshape(it[:,0],(N,N)), np.reshape(it[:,1],(N,N)), np.reshape(result,(N,N))) 
# where N = x.size still 

结果:

请注意,我会将此对象简单地称为一个平面:“3d 超平面”可能有点夸大其词。