Python之Numpy:二元函數繪制/三維數據可視化/3D


意義

在機器學習任務中選擇計算模型或者學習數學時,可視化有助於研究函數值的變化趨勢(觀察收斂、分布、幾何形狀等),帶來直觀的感受。

源碼

# 繪制二元函數
    # 參考文獻
    #    + python畫二元函數的圖像(3D) https://blog.csdn.net/your_answer/article/details/79135076
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import pyplot as plt
 
fig = plt.figure()
ax = Axes3D(fig)
# x=np.arange(-2*np.pi,2*np.pi,0.1) # np.range(startValue,endValue, stepSize)
# y=np.arange(-2*np.pi,2*np.pi,0.1)
# x = np.random.rand(100) # np.random.rand(4) # 生成一維數組 形如: array([ 0.69804514, 0.48808425, 0.79440667, 0.66959075]);
# y = np.random.rand(100)
# x = np.arange(1,100,1) # np.random.rand(4) # 生成一維數組 形如: array([ 0.69804514, 0.48808425, 0.79440667, 0.66959075]);
# y = np.arange(1,100,1)
x = np.random.randint(100,size=100) # np.random.randint(20,size=10) 形如: array([4, 1, 4, 3, 8, 2, 8, 5, 8, 19])
y = np.random.randint(100,size=100)

X, Y = np.meshgrid(x, y) # [important] 創建網格 np.meshgrid(xnums,ynums)

    # Z = np.sin(X)*np.cos(Y) # 創建二元函數關系
Z = 1 / (np.log(X)*np.log(Y));

plt.xlabel('x')
plt.ylabel('y')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
plt.show()

繪制曲線圖/一元函數

  • 示例一
    # 繪制曲線圖
import matplotlib.pyplot as plt

def plotLineChart():
    fig  = plt.figure()
    ax = fig.add_subplot(1,1,1) # numrows, numcols, fignum ; fignum標識了該子圖的順序,其范圍從1到numrows*numcols
    ax.set_title("axes title");
    ax.set_xlabel("x label")      
    ax.set_ylabel("y label")
    ax.plot([1,2,3,4],[2,3,4,5])
    plt.show()
    pass;

plotDemo();
  • 示例二(進階)
# encoding=utf-8
import matplotlib.pyplot as plt
from pylab import *                                 #支持中文
mpl.rcParams['font.sans-serif'] = ['SimHei']

names = ['5', '10', '15', '20', '25']
x = range(len(names))
y1 = [0.855, 0.84, 0.835, 0.815, 0.81]
y2=[0.86,0.85,0.853,0.849,0.83]
    #plt.plot(x, y1, 'ro-')
    #plt.plot(x, y2, 'bo-')
    #pl.xlim(-1, 11)  # 限定橫軸的范圍
    #pl.ylim(-1, 110)  # 限定縱軸的范圍
plt.plot(x, y1, marker='o', mec='r', mfc='w',label=u'y=x^2曲線圖')
plt.plot(x, y2, marker='*', ms=10,label=u'y=x^3曲線圖')
plt.legend()  # 讓圖例生效
plt.xticks(x, names, rotation=45)
plt.margins(0)
plt.subplots_adjust(bottom=0.15)
plt.xlabel(u"time(s)鄰居") #X軸標簽
plt.ylabel("RMSE") #Y軸標簽
plt.title("A simple plot") #標題

plt.show()

參考文獻

推薦工具


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM