注意
跳到結尾以下載完整範例程式碼。
繪製最佳化解空間的輪廓#
在說明最佳化問題的解空間時,輪廓繪圖特別方便。不僅可以使用 axes.Axes.contour
來表示目標函數的地形,還可以用它來產生約束函數的邊界曲線。可以使用 TickedStroke
繪製約束線,以區分約束邊界的有效和無效側。
axes.Axes.contour
會產生曲線,其較大值位於輪廓的左側。角度參數以零度向前測量,值向左增加。因此,當在典型最佳化問題中使用 TickedStroke
來說明約束時,角度應設定在零到 180 度之間。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects
fig, ax = plt.subplots(figsize=(6, 6))
nx = 101
ny = 105
# Set up survey vectors
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)
# Set up survey matrices. Design disk loading and gear ratio.
x1, x2 = np.meshgrid(xvec, yvec)
# Evaluate some stuff to plot
obj = x1**2 + x2**2 - 2*x1 - 2*x2 + 2
g1 = -(3*x1 + x2 - 5.5)
g2 = -(x1 + 2*x2 - 4.5)
g3 = 0.8 + x1**-3 - x2
cntr = ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16],
colors='black')
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)
cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
cg1.set(path_effects=[patheffects.withTickedStroke(angle=135)])
cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
cg2.set(path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
cg3.set(path_effects=[patheffects.withTickedStroke(spacing=7)])
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
plt.show()
腳本的總執行時間: (0 分 1.283 秒)