溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用pythonUIUI繪制Axes3D

發(fā)布時間:2021-04-30 15:53:27 來源:億速云 閱讀:158 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)如何使用pythonUIUI繪制Axes3D,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

python有哪些常用庫

python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

首先,根據(jù)題意確定目標函數(shù):f(w1,w2) = w1^2 + w2^2 + 2 w1 w2 + 500
然后,針對w1,w2分別求偏導(dǎo),編寫主方法求極值點
而后,創(chuàng)建三維坐標系繪制函數(shù)圖像以及其極值點即可

具體代碼實現(xiàn)以及成像結(jié)果如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

#f(w1,w2) = w1^2 + w2^2 + 2*w1*w2 + 500
def targetFunction(W): #目標函數(shù)
 w1,w2 = W
 return w1 ** 2 + w2**2 + 2*w1*w2+500

def gradientFunction(W): #梯度函數(shù):分別對w1,w2求偏導(dǎo)
 w1,w2 = W
 w1_grad = 2*w1+2*w2
 w2_grad = 2*w2 + 2*w1
 return np.array([w1_grad,w2_grad])

def batch_gradient_distance(targetFunc,gradientFunc,init_W,learning_rate = 0.01,tolerance = 0.0000001): #核心算法
 W = init_W
 target_value = targetFunc(W)
 counts = 0 #用于計算次數(shù)
 while counts<5000:
 gradient = gradientFunc(W)
 next_W = W-gradient*learning_rate
 next_target_value = targetFunc(next_W)
 if abs(next_target_value-target_value) <tolerance:
 print("此結(jié)果經(jīng)過了", counts, "次循環(huán)")
 return next_W
 else:
 W,target_value = next_W,next_target_value
 counts += 1
 else:
 print("沒有取到極值點")


if __name__ == '__main__':
 np.random.seed(0) #保證每次運行隨機出來的結(jié)果一致
 init_W = np.array([np.random.random(),np.random.random()]) #隨機初始的w1,w2
 w1,w2 = batch_gradient_distance(targetFunction,gradientFunction,init_W)
 print(w1,w2)
 #畫圖
 x1=np.arange(-10,11,1) #為了繪制函數(shù)的原圖像
 x2=np.arange(-10,11,1)

 x1, x2 = np.meshgrid(x1, x2) # meshgrid :3D坐標系

 z=x1**2 + x2**2 + 2*x1*x2+500

 fig = plt.figure()
 ax = Axes3D(fig)
 ax.plot_surface(x1, x2, z) #繪制3D坐標系中的函數(shù)圖像
 ax.scatter(w1,w2, targetFunction([w1,w2]), s=50, c='red') #繪制已經(jīng)找到的極值點
 ax.legend() #使坐標系為網(wǎng)格狀

 plt.show() #顯示

函數(shù)以及其極值點成像如下(紅點為極值點):

如何使用pythonUIUI繪制Axes3D

關(guān)于如何使用pythonUIUI繪制Axes3D就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI