如何在Python的等高线图上绘制梯度向量

4

我有一个关于两个变量W1和W2的损失函数,输出结果为z=F(W1, W2)。

现在,我绘制了这个损失函数的等高线图。现在假设我已经在两个点处计算了梯度向量,因此我现在有了两个梯度向量。我想在我的等高线图上绘制这些梯度向量,但我不知道该如何处理。欢迎提供任何帮助。

enter code here
%matplotlib inline
import matplotlib.pyplot as plt 
import numpy as np 

feature_x = np.arange(-50, 50, 2) 
feature_y = np.arange(-50, 50, 3) 

# Creating 2-D grid of features 
[X, Y] = np.meshgrid(feature_x, feature_y) 

fig, ax = plt.subplots(1, 1) 

z = 0.5*np.array((Y-X)*(Y-X) + 0.5*(1-X)*(1-X))

# plots contour lines 
ax.contour(X, Y, z, 10, cmap = 'jet') 
ax.grid(True)
ax.axis('scaled')
#ax.clabel(cp, inline=1, fontsize=10)  
ax.set_title('Contour Plot') 
ax.set_xlabel('feature_x') 
ax.set_ylabel('feature_y') 

plt.show() 
1个回答

5
你可以使用FancyArrowPatch在几个选定的位置绘制渐变。
from matplotlib.patches import FancyArrowPatch
x1 = -20     # position of the gradient
y1 = 10
dz1_dx = 10  # value of the gradient at that position
dz1_dy = -5
arrow = FancyArrowPatch((x1, y1), (x1+dz1_dx, y1+dz1_dy),    
                        arrowstyle='simple', color='k', mutation_scale=10)
ax.add_patch(arrow)

带箭头的等高线图 否则,如果您想绘制整个向量场,quiver可能是一个选项:

feature_x = np.arange(-50, 50, 2)
feature_y = np.arange(-50, 50, 2)

x, y = np.meshgrid(feature_x, feature_y)
z = 0.5*(y-x)**2 + 0.5*(1-x)**2
u = 2*x - y - 1
v = y - x

# Normalize all gradients to focus on the direction not the magnitude
norm = np.linalg.norm(np.array((u, v)), axis=0)
u = u / norm
v = v / norm

fig, ax = plt.subplots(1, 1)
ax.set_aspect(1)
ax.plot(feature_x, feature_y, c='k')
ax.quiver(x, y, u, v, units='xy', scale=0.5, color='gray')
ax.contour(x, y, z, 10, cmap='jet', lw=2)

arrow = FancyArrowPatch((35, 35), (35+34*0.2, 35+0), arrowstyle='simple',
                        color='r', mutation_scale=10)  
ax.add_patch(arrow)  # NOTE: this gradient is scaled to make it better visible

渐变场

我在这个图中添加了线 y = x,并标出了该直线与等高线相交的点。从这里可以清楚地看到:

梯度与等值面垂直

因此,对于您的点(80,80),梯度(79,0)是正确的,即使等高线的一般形状可能表明应该有一个y方向的部分。但是,如果沿着y = x线看,您会发现那里的梯度总是只在x方向上。


1
我更新了我的答案,并包括了第二个例子,在那里我绘制了整个向量场,希望这能让事情更清晰。但是对于位置/坐标(80, 80),梯度为(79, 0) - scleronomic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接