相關概念:
1.x向量和y向量

import numpy as np import matplotlib.pyplot as plt x = np.array([[0,1,2,3], [0,0,0,0], [0,0,0,0], [0,0,0,0]]) y = np.array([[0,0,0,0], [1,0,0,0], [2,0,0,0], [3,0,0,0]]) plt.plot(x,y, color = 'red', ##全部點設置紅色 marker='o', ##形狀:實心圓圈 linestyle = '') ##線性:空 點與點間不連線 plt.grid(True) ##顯示網格 plt.show()
x向量:[0, 1, 2, 3]
y向量:[0, 1, 2, 3]
2.xv和yv矩陣

import numpy as np import matplotlib.pyplot as plt x = [0,1,2,3] y = [0,1,2,3] print(x) print(y) x,y = np.meshgrid(x,y) print(x) print(y) plt.plot(x,y, color = 'red', ##全部點設置紅色 marker='o', ##形狀:實心圓圈 linestyle = '') ##線性:空 點與點間不連線 plt.grid(True) ##顯示網格 plt.show()
xv坐標矩陣:
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
yv坐標矩陣:
[[0 0 0 0]
[1 1 1 1]
[2 2 2 2]
[3 3 3 3]]
z:網格平面坐標
圖片來源:https://www.cnblogs.com/lantingg/p/9082333.html

import numpy as np import matplotlib.pyplot as plt #調用meshgrid實現以上功能 x = np.linspace(0,100,11) y = np.linspace(0,50,11) print(x) print(y) x,y = np.meshgrid(x,y) print('x--meshgrid后的數據',x) print('y--meshgrid后的數據',y) plt.plot(x,y, color = 'red', ##全部點設置紅色 marker='o', ##形狀:實心圓圈 linestyle = '') ##線性:空 點與點間不連線 plt.grid(True) ##顯示網格 plt.show() ''' x = [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] y = [ 0. 5. 10. 15. 20. 25. 30. 35. 40. 45. 50.] x--meshgrid后的數據 [將x一維數組,重復11次] [[ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] [ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.]] y--meshgrid后的數據 [將y一位數組轉置成列,再重復11次] [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 5. 5. 5. 5. 5. 5. 5. 5. 5. 5. 5.] [10. 10. 10. 10. 10. 10. 10. 10. 10. 10. 10.] [15. 15. 15. 15. 15. 15. 15. 15. 15. 15. 15.] [20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20.] [25. 25. 25. 25. 25. 25. 25. 25. 25. 25. 25.] [30. 30. 30. 30. 30. 30. 30. 30. 30. 30. 30.] [35. 35. 35. 35. 35. 35. 35. 35. 35. 35. 35.] [40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40.] [45. 45. 45. 45. 45. 45. 45. 45. 45. 45. 45.] [50. 50. 50. 50. 50. 50. 50. 50. 50. 50. 50.]] '''

import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot_3d(): fig = plt.figure(figsize=(12,8)) ax = Axes3D(fig) x = np.arange(-2,2,0.05) y = np.arange(-2,2,0.05) ##對x,y數據執行網格化 x,y = np.meshgrid(x,y) z1 = np.exp(-x**2-y**2) z2 = np.exp(-(x-1)**2-(y-1)**2) z = -(z1-z2)*2 ax.plot_surface(x,y,z, ##x,y,z二維矩陣(坐標矩陣xv,yv,zv) rstride=1,##retride(row)指定行的跨度 cstride=1,##retride(column)指定列的跨度 cmap='rainbow') ##設置顏色映射 ##設置z軸范圍 ax.set_zlim(-2,2) ##設置標題 plt.title('優化設計之梯度下降--目標函數',fontproperties = 'SimHei',fontsize = 20) plt.show() ax.plot_surface() plot_3d()

def plot_axes3d_wireframe(): fig = plt.figure(figsize=(12,8)) ax = Axes3D(fig) x = np.arange(-2,2,0.05) y = np.arange(-2,2,0.05) ##對x,y數據執行網格化 x,y = np.meshgrid(x,y) z1 = np.exp(-x**2-y**2) z2 = np.exp(-(x-1)**2-(y-1)**2) z = -(z1-z2)*2 ax.plot_wireframe(x,y,z, ##x,y,z二維矩陣(坐標矩陣xv,yv,zv) rstride=1,##retride(row)指定行的跨度 cstride=1,##retride(column)指定列的跨度 cmap='rainbow') ##設置顏色映射 ##設置z軸范圍 ax.set_zlim(-2,2) ##設置標題 plt.title('優化設計之梯度下降--目標函數',fontproperties = 'SimHei',fontsize = 20) plt.show() plot_axes3d_wireframe()
###二維散點圖

##二維散點圖 ''' matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs) x,y 平面點位置 s控制節點大小 c對應顏色值,c=x使點的顏色根據點的x值變化 cmap:顏色映射 marker:控制節點形狀 alpha:控制節點透明度 ''' import numpy as np import matplotlib.pyplot as plt ##二維散點圖 fig = plt.figure() x = np.arange(100) y = np.random.randn(100) plt.scatter(x,y,c='b') plt.scatter(x+4,y,c='b',alpha=0.5) plt.show()
##三維散點圖
'''
p3d.Axes3D.scatter( xs, ys, zs=0, zdir=’z’, s=20, c=None, depthshade=True,
*args, **kwargs )
p3d.Axes3D.scatter3D( xs, ys, zs=0, zdir=’z’, s=20, c=None, depthshade=True,
*args, **kwargs)
xs,ys 代表點x,y軸坐標
zs代表z軸坐標:第一種,標量z=0 在空間平面z=0畫圖,第二種z與xs,yx同樣shape的數組
'''

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) x = np.arange(100) y = np.random.randn(100) ax.scatter(x,y,c='b',s=10,alpha=0.5) ##默認z=0平面 ax.scatter(x+4,y,c='b',s=10,alpha=0.7) ax.scatter(x+4,y,2,c='b',s=10,alpha=0.7) ##指定z=2平面 plt.show()

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) z = 6*np.random.randn(5000) x = np.sin(z) y = np.cos(z) ax.scatter(x,y,z,c='b',s=10,alpha=0.5) plt.show()

'''二維梯度下降法''' def func_2d_single(x,y): ''' 目標函數傳入x,y :param x,y: 自變量,一維向量 :return: 因變量,標量 ''' z1 = np.exp(-x**2-y**2) z2 = np.exp(-(x-1)**2-(y-1)**2) z = -(z1-2*z2)*0.5 return z def func_2d(xy): ''' 目標函數傳入xy組成的數組,如[x1,y1] :param xy: 自變量,二維向量 (x,y) :return: 因變量,標量 ''' z1 = np.exp(-xy[0]**2-xy[1]**2) z2 = np.exp(-(xy[0]-1)**2-(xy[1]-1)**2) z = -(z1-2*z2)*0.5 return z def grad_2d(xy): ''' 目標函數的梯度 :param xy: 自變量,二維向量 :return: 因變量,二維向量 (分別求偏導數,組成數組返回) ''' grad_x = 2*xy[0]*(np.exp(-(xy[0]**2+xy[1]**2))) grad_y = 2*xy[1]*(np.exp(-(xy[0]**2+xy[1]**2))) return np.array([grad_x,grad_y]) def gradient_descent_2d(grad, cur_xy=np.array([1, 1]), learning_rate=0.001, precision=0.001, max_iters=100000000): ''' 二維目標函數的梯度下降法 :param grad: 目標函數的梯度 :param cur_xy: 當前的x和y值 :param learning_rate: 學習率 :param precision: 收斂精度 :param max_iters: 最大迭代次數 :return: 返回極小值 ''' print(f"{cur_xy} 作為初始值開始的迭代......") x_cur_list = [] y_cur_list = [] for i in tqdm(range(max_iters)): grad_cur = grad(cur_xy) ##創建兩個列表,用於接收變化的x,y x_cur_list.append(cur_xy[0]) y_cur_list.append(cur_xy[1]) if np.linalg.norm(grad_cur,ord=2)<precision: ##求范數,ord=2 平方和開根 break ###當梯度接近於0時,視為收斂 cur_xy = cur_xy-grad_cur*learning_rate x_cur_list.append(cur_xy[0]) y_cur_list.append(cur_xy[1]) print('第%s次迭代:x,y = %s'%(i,cur_xy)) print('極小值 x,y = %s '%cur_xy) return (x_cur_list,y_cur_list) if __name__=="__main__": current_xy_list = gradient_descent_2d(grad_2d) fig = plt.figure(figsize=(12,8)) ax = Axes3D(fig) a = np.array(current_xy_list[0]) b = np.array(current_xy_list[1]) c = func_2d_single(a,b) ax.scatter(a,b,c,c='Black',s=10,alpha=1,marker='o') x = np.arange(-2,2,0.05) y = np.arange(-2,2,0.05) ##對x,y數據執行網格化 x,y = np.meshgrid(x,y) z = func_2d_single(x,y) ax.plot_surface(x,y,z, rstride=1,##retride(row)指定行的跨度 cstride=1,##retride(column)指定列的跨度 cmap='rainbow', alpha=0.3 ) ##設置顏色映射 # ax.plot_wireframe(x,y,z,) ##設置z軸范圍 ax.set_zlim(-2,2) ##設置標題 plt.title('汽車優化設計之梯度下降--二元函數',fontproperties = 'SimHei',fontsize = 20) plt.xlabel('x',fontproperties = 'SimHei',fontsize = 20) plt.ylabel('y', fontproperties='SimHei', fontsize=20) plt.show()