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

意義

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

源碼

# 繪製二元函數
    # 參考文獻
    #    + 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()

參考文獻

推薦工具

相關文章
相關標籤/搜索