標籤:

Python優雅地可視化數據

作者: 冰不語

原文鏈接:jianshu.com/p/07a7c60a0

查看更多專業文章,請移步至「人工智慧LeadAI」公眾號,查看更多的課程信息和產品信息,請移至全新打造的官網:www.leadai.org.

正文共3425個字,9張圖,預計閱讀時間9分鐘。

最近看《機器學習系統設計》。學到了一些用Matplotlib進行數據可視化的方法。在這裡整理一下。

聲明:由於本文的代碼大部分是參考書中的例子,所以不提供完整代碼,只提供示例片段,也就是只能看出某一部分用法,感興趣的需要在自己的數據上學習測試。

最開始,當然還是要導入我們需要的包:

# -*- coding=utf-8 -*-nfrom matplotlib import pyplot as pltnfrom sklearn.datasets nimport load_irisnimport numpy as npnimport itertoolsn

01

畫散點圖

畫散點圖用plt.scatter(x,y)。畫連續曲線在下一個例子中可以看到,用到了plt.plot(x,y)。

plt.xticks(loc,label)可以自定義x軸刻度的顯示,第一個參數表示的是第二個參數label顯示的位置loc。

plt.autoscale(tight=True)可以自動調整圖像顯示的最佳化比例 。

plt.scatter(x,y)nplt.title("Web traffic")nplt.xlabel("Time")nplt.ylabel("Hits/hour")nplt.xticks([w*7*24 for w in range(10)],[week %i %w for w in range(10)])nplt.autoscale(tight=True)nplt.grid()##plt.show()n

畫出散點圖如下:

散點圖

項式擬合併畫出擬合曲線

## 多項式擬合fp2 = np.polyfit(x,y,3)nf2 = np.poly1d(fp2)nnfx = np.linspace(0,x[-1],1000)nplt.plot(fx,f2(fx),linewidth_=4,color=g)## f2.order: 函數的階數plt.legend(["d=%i" % f2.order],loc="upper right")nplt.show()n

效果圖

曲線擬合

02

畫多個子圖

這裡用到的是sklearn的iris_dataset(鳶尾花數據集)。

此數據集包含四列,分別是鳶尾花的四個特徵:

  • sepal length (cm)——花萼長度
  • sepal width (cm)——花萼寬度
  • petal length (cm)——花瓣長度
  • petal width (cm)——花瓣寬度

這裡首先對數據進行一定的處理,主要就是對特徵名稱進行兩兩排列組合,然後任兩個特徵一個一個做x軸另一個做y軸進行畫圖。

# -*- coding=utf-8 -*-from matplotlib import pyplot as pltfrom sklearn.datasets import load_irisimport numpy as npimport itertoolsnndata = load_iris()#print(data.data)#print(data.feature_names)#print(data.target)features = data[data]nfeature_names = data[feature_names]ntarget = data[target]nlabels = data[target_names][data[target]]nnprint(data.data)nprint(data.feature_names)n

這裡有一個排列組合參考代碼,最後是取出了兩兩組合的情況。

排列組合的結果是feature_names_2包含了排列組合的所有情況,它的每一個元素包含了一個排列組合的所有情況,比如第一個元素包含了所有單個元素排列組合的情況,第二個元素包含了所有的兩兩組合的情況......所以這裡取出了第二個元素,也就是所有的兩兩組合的情況。

feature_names_2 = []#排列組合for i in range(1,len(feature_names)+1):n iter = itertools.combinations(feature_names,i)n feature_names_2.append(list(iter))n nprint(len(feature_names_2[1]))for i in feature_names_2[1]:n print(i)n

下面是在for循環里畫多個子圖的方法。對我來說,這裡需要學習的有不少。比如

  • for i,k in enumerate(feature_names_2[1]):這一句老是記不住。
  • 比如從列表中取出某元素所在的索引的方法:index1 = feature_names.index(k[0]),也即index = list.index(element)的形式。
  • 比如for循環中畫子圖的方法:plt.subplot(2,3,1+i)
  • 比如for循環的下面這用法:for t,marker,c in zip(range(3),">ox","rgb"):

plt.figure(1)for i,k in enumerate(feature_names_2[1]):n index1 = feature_names.index(k[0])n index2 = feature_names.index(k[1])n plt.subplot(2,3,1+i) for t,marker,c in zip(range(3),">ox","rgb"): n plt.scatter(features[target==t,index1],features[target==t,index2],marker=marker,c=c)n plt.xlabel(k[0])n plt.ylabel(k[1])n plt.xticks([])n plt.yticks([])n plt.autoscale()n plt.tight_layout() nplt.show()n

這裡的可視化效果如下:

多個子圖

03

畫水平線和垂直線

比如在上面最後一幅圖中,找到了一種方法可以把三種鳶尾花分出來,這是我們需要畫出模型(一條直線)。這個時候怎麼畫呢?

下面需要注意的就是plt.vlines(x,y_min,y_max)和plt.hlines(y,x_min,x_max)的用法。

plt.figure(2)for t,marker,c in zip(range(3),">ox","rgb"): n plt.scatter(features[target==t,3],features[target==t,2],marker=marker,c=c)n plt.xlabel(feature_names[3])n plt.ylabel(feature_names[2]) # plt.xticks([]) # plt.yticks([])n plt.autoscale() nplt.vlines(1.6, 0, 8, colors = "c",linewidth_=4,linestyles = "dashed")nplt.hlines(2.5, 0, 2.5, colors = "y",linewidth_=4,linestyles = "dashed")nplt.show()n

此時可視化效果如下:

豎直線和水平線

04

動態畫圖

plt.ion()打開交互模式。plt.show()不再阻塞程序運行。

注意plt.axis()的用法。

plt.axis([0, 100, 0, 1])nplt.ion()for i in range(100):n y = np.random.random()n plt.autoscale()n plt.scatter(i, y)n plt.pause(0.01)n

可視化效果:

動態畫圖


推薦閱讀:

TAG:Python |