pytorch實(shí)踐線性模型3d詳解
y = wx +b
通過meshgrid 得到兩個(gè)二維矩陣
關(guān)鍵理解:
plot_surface需要的xyz是二維np數(shù)組
這里提前準(zhǔn)備meshgrid來生產(chǎn)x和y需要的參數(shù)
下圖的W和I即plot_surface需要xy
Z即我們需要的權(quán)重?fù)p失
計(jì)算方式要和W,I. I的每行中內(nèi)容是一樣的就是y=wx+b的b是一樣的
fig = plt.figure() ax = fig.add_axes(Axes3D(fig)) ax.plot_surface(W, I, Z=MSE_data)
總的實(shí)驗(yàn)代碼
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D class LinearModel: @staticmethod def forward(w, x): return w * x @staticmethod def forward_with_intercept(w, x, b): return w * x + b @staticmethod def get_loss(w, x, y_origin, exp=2, b=None): if b: y = LinearModel.forward_with_intercept(w, x, b) else: y = LinearModel.forward(w, x) return pow(y_origin - y, exp) def test_2d(): x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] weight_data = [] MSE_data = [] # 設(shè)定實(shí)驗(yàn)的權(quán)重范圍 for w in np.arange(0.0, 4.1, 0.1): weight_data.append(w) loss_total = 0 # 計(jì)算每個(gè)權(quán)重在數(shù)據(jù)集上的MSE平均平方方差 for x_val, y_val in zip(x_data, y_data): loss_total += LinearModel.get_loss(w, x_val, y_val) MSE_data.append(loss_total / len(x_data)) # 繪圖 plt.xlabel("weight") plt.ylabel("MSE") plt.plot(weight_data, MSE_data) plt.show() def test_3d(): x_data = [1.0, 2.0, 3.0] y_data = [5.0, 8.0, 11.0] weight_data = np.arange(0.0, 4.1, 0.1) intercept_data = np.arange(0.0, 4.1, 0.1) W, I = np.meshgrid(weight_data, intercept_data) MSE_data = [] # 設(shè)定實(shí)驗(yàn)的權(quán)重范圍 循環(huán)要先寫截距的 meshgrid 的返回第二個(gè)是相當(dāng)于41*41 同一行值相同 ,要在第二層循環(huán)去遍歷權(quán)重 for intercept in intercept_data: MSE_data_tmp = [] for w in weight_data: loss_total = 0 # 計(jì)算每個(gè)權(quán)重在數(shù)據(jù)集上的MSE平均平方方差 for x_val, y_val in zip(x_data, y_data): loss_total += LinearModel.get_loss(w, x_val, y_val, b=intercept) MSE_data_tmp.append(loss_total / len(x_data)) MSE_data.append(MSE_data_tmp) MSE_data = np.array(MSE_data) fig = plt.figure() ax = fig.add_axes(Axes3D(fig)) ax.plot_surface(W, I, Z=MSE_data) plt.xlabel("weight") plt.ylabel("intercept") plt.show() if __name__ == '__main__': test_2d() test_3d()
到此這篇關(guān)于pytorch實(shí)踐線性模型3d的文章就介紹到這了,更多相關(guān)pytorch線性模型內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
django表單中的按鈕獲取數(shù)據(jù)的實(shí)例分析
在本篇文章里小編給大家詳解了關(guān)于django表單中的按鈕獲取數(shù)據(jù)的內(nèi)容,需要的朋友們可以參考下。2020-07-07Python如何使用qrcode生成指定內(nèi)容的二維碼并在GUI界面顯示
現(xiàn)在二維碼很流行,大街小巷大小商品廣告上的二維碼標(biāo)簽都隨處可見,下面這篇文章主要給大家介紹了關(guān)于如何使用qrcode生成指定內(nèi)容的二維碼并在GUI界面顯示的相關(guān)資料,需要的朋友可以參考下2022-09-09django實(shí)現(xiàn)后臺(tái)顯示媒體文件
這篇文章主要介紹了django實(shí)現(xiàn)后臺(tái)顯示媒體文件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04python實(shí)現(xiàn)的文件同步服務(wù)器實(shí)例
這篇文章主要介紹了python實(shí)現(xiàn)的文件同步服務(wù)器,實(shí)例分析了文件同步服務(wù)器的原理及客戶端、服務(wù)端的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-06-06Python日期時(shí)間對(duì)象轉(zhuǎn)換為字符串的實(shí)例
今天小編就為大家分享一篇Python日期時(shí)間對(duì)象轉(zhuǎn)換為字符串的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06