python機器學習-sklearn挖掘乳腺癌細胞( 博主親自錄製)html
網易雲觀看地址python
機器學習,統計項目合做QQ:231469242github
http://www.kancloud.cn/wizardforcel/scipy-lecture-notes/129866參考shell
Matplotlib 多是Python唯一一個最普遍使用的二維圖包。它同時提供了從Python中可視化數據很是的快速方式以及多種格式的出版質量圖片。咱們將在交互模式下研究Matplotlib,包含大多數的經常使用案例。api
IPython是強化版交互Python shell,有許多有趣的功能,包括:輸入輸出的命名、訪問shell命令改進錯誤排除等。它位於Python中的科學計算工做流的核心,要讓它與Matplotlib的結合使用:數組
用命令行參數 -pylab
(--pylab
從IPython0.12開始)啓動IPython,得到帶有Matlab/Mathematica相似功能的交互Matplotlib session。session
pylab提供了matplotlib面向對象的繪圖庫的程序接口。它的模型與Matlab™很是相近。所以,pylab中的絕大多數繪圖命令Matlab™都有帶有類似函數的相似實現。重要的命令會以交互例子來解釋。app
在這個部分,咱們將在同一個圖像中繪製cosine和sine函數。從默認設置開始,咱們將不斷豐富圖片,讓它看起來更漂亮。框架
第一步得到sine和cosine函數的數據:
In [2]:
import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X)
X
如今是Numpy數組,範圍是-π
到+π
之間(包含)的256個值。C是cosine(256個值),而S是sine(256個值)
要運行例子,你能夠在IPython的交互session中輸入這些命令:
ipython --pylab
這會將咱們帶到IPython提示符:
IPython 2.3.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. Using matplotlib backend: MacOSX
你能夠下載每一個示例,而後用日常的Python運行,可是,你將無法動態的數據操做:
python exercice_1.py
經過點擊對應的圖片,你能夠得到每一步的源碼。
提示:文檔
Matplotlib有一組默認設置,容許自定義全部的屬性。你幾乎能夠控制在matplotlib中的全部屬性:圖片大小和dpi、線長度、顏色和樣式、座標軸、座標軸和網格屬性、文本和字體屬性等等。
import pylab as pl import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) pl.plot(X, C) pl.plot(X, S) pl.show()
提示:文檔
在下面的腳本中,咱們標示(備註)了影響繪圖外觀的全部圖片設置。
這些設置被顯式的設置爲默認值,可是如今你能夠交互的實驗這些值以便驗證他們的效果(看一下下面的線屬性和線樣式)。
import pylab as pl import numpy as np # 建立一個大小爲 8X6 英寸,每英寸80個點的圖片 pl.figure(figsize=(8, 6), dpi=80) # 從1X1的網格建立一個子圖片 pl.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # 用寬度爲1(像素)的藍色連續直線繪製cosine pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # 用寬度爲1(像素)的綠色連續直線繪製sine pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") # 設置x軸的極值 pl.xlim(-4.0, 4.0) # 設置x軸的刻度值 pl.xticks(np.linspace(-4, 4, 9, endpoint=True)) # 設置y軸的極值 pl.ylim(-1.0, 1.0) # 設置y軸的刻度值 pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) # 用72dpi保存圖片 # savefig("exercice_2.png", dpi=72) # 在屏幕上顯示結果 pl.show()
提示:文檔
首先,咱們想要cosine是藍色,sine是紅色,二者都是稍稍粗一點的線。咱們也改變了一點圖片的大小,讓它更加水平。
pl.figure(figsize=(10, 6), dpi=80) pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") pl.plot(X, S, color="red", linewidth=2.5, linestyle="-")
提示:文檔
當前的圖片的極值限制太擁擠了,咱們但願留一點空間以便清晰的看到全部的數據點。
pl.xlim(X.min() * 1.1, X.max() * 1.1) pl.ylim(C.min() * 1.1, C.max() * 1.1)
提示:文檔
如今的刻度不太理想,由於他們沒有顯示對於sine和cosine有意義的值(+/-π,+/-π/2)。咱們將改變這些刻度,讓他們只顯示這些值。
pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) pl.yticks([-1, 0, +1])
提示:文檔
刻度如今放在了正確的位置,可是標籤並非顯而易見。咱們能想到3.14是π,可是最好讓它更明確。
當咱們設置了刻度值,咱們也能夠在第二個參數中列出對應的標籤。注意咱們用latex以便更好的渲染標籤。
pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) pl.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'])
提示:文檔
脊柱是鏈接座標軸刻度標記的線,記錄了數據範圍的邊界。他們能夠被放在任意的位置,到目前位置,他們被放在了座標軸的四周。咱們將改變他們,由於我 們但願他們在中間。由於有四條(上下左右),咱們經過設置顏色爲None捨棄了頂部和右側,而且咱們將把底部和左側的脊柱移動到數據空間座標的零點。
ax = pl.gca() # gca stands for 'get current axis' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0))
提示:文檔
讓咱們在坐上角添加圖例。這隻須要在plot命裏中添加關鍵詞參數label(將被用於圖例框)。
pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") pl.legend(loc='upper left')
提示:文檔
讓咱們用annotate命令標註一些有趣的點。咱們選取值2π/3,咱們想要標註sine和cosine。首先咱們在曲線上畫出了一個垂直的散點標記線。而後,咱們將用annotate命令顯示帶有剪頭的文字。
t = 2 * np.pi / 3 pl.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") pl.scatter([t, ], [np.cos(t), ], 50, color='blue') pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) pl.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") pl.scatter([t, ],[np.sin(t), ], 50, color='red') pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
提示:文檔
由於藍色和紅色的線,刻度標籤很難看到。咱們可讓他們更大一些,也能夠調整他們的屬性以便他們被處理爲半透明的白色背景。這樣咱們就能夠同時看到數據和標籤。
for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
在matplotlib中「圖形」是用戶界面中的整個窗口。在這個圖形中能夠有「子圖」。
到目前爲止,咱們已經使用圖形和建立數軸。這對於快速繪圖是很是方便的。使用圖形、子圖和軸咱們能夠控制顯示。儘管子圖將圖表放在標準的網格中,軸 能夠在圖形中放在任意位置。根據你的目的不一樣,兩者都很是有用。咱們也在沒有顯式的調用圖形和子圖時使用了他們。當咱們調用plot 時,matplotlib調用gca()
來得到當前的座標軸,相應的調用gcf()
得到當前的圖形。若是沒有當前圖形,那麼將調用figure()
去建立一個,嚴格來講是建立一個`subplot(111)。讓咱們來詳細看一下。
圖形是在GUI中的窗口,標題是"Figure #"。圖形的標號從1開始,而不是常規的Python方式從0開始。這明顯是MATLAB-風格。這些參數決定圖形的外觀:
參數 | 默認值 | 描述 |
---|---|---|
num | 1 | 圖形編號 |
figsize | figure.figsize | 以英寸表示的圖形大小(寬、高) |
dpi | figure.dpi | 分辨率以每英寸點數表示 |
facecolor | figure.facecolor | 背景色 |
edgecolor | figure.edgecolor | 背景邊緣色 |
frameon | True | 是否繪製框架 |
默認值能夠在資源文件中指明,並在絕大數時間使用。只有圖形數常常被改變。
與其餘對象相似,你能夠用setp或者set_something方法設置圖形屬性。
當你使用GUI工做時,你能夠點擊右上的X關閉圖形。可是,你能夠經過調用close用程序關閉圖形。根據參數關閉不一樣內容(1)當前圖形(沒有參數),(2)特定圖形(用圖形編號或圖形實例作參數),(3)全部圖形("all"做爲參數)。
pl.close(1) # Closes figure 1
用子圖你能夠將圖片放置在標準方格中。你須要指定行列數和圖片數。 注意gridspec命令相對更加高級。
軸與子圖很是相似,不過容許圖形放在圖片的任意位置。所以,若是咱們想要將一個小圖形放在一個更大圖形中,咱們能夠用軸。
格式良好的刻度是準備好發佈圖片的必要部分。Matplotlib提供了一個徹底可控的刻度系統。有刻度位置來指定刻度該出如今哪,還有刻度格式來給出你想要的刻度外觀。主刻度和子刻度能夠被獨立放置和整理格式。以前子刻度默認是不顯示的,即他們只有空列表,由於它是NullLocator
(見下面)。
刻度位置能夠控制的位置。它的設置以下:
ax = pl.gca() ax.xaxis.set_major_locator(eval(locator))
不一樣的需求有多種位置:
全部這些位置均可以從基礎類matplotlib.ticker.Locator衍生出來。你能夠從中衍生出你本身的位置。將日期處理爲刻度特別困哪。所以,matplotlib
提供了特殊的位置matplotlib.dates
。
提示:你可使用fill_between命令。
從下面的代碼開始,試着從新生成這個圖片,當心處理填充區域:
n = 256 X = np.linspace(-np.pi, np.pi, n, endpoint=True) Y = np.sin(2 * X) pl.plot(X, Y + 1, color='blue', alpha=1.00) pl.plot(X, Y - 1, color='blue', alpha=1.00)
點擊圖片查看答案。
提示:顏色根據角度進行分配
從下面的代碼開始,試着從新生成這個圖片,當心處理標記的大小顏色和透明度:
n = 1024 X = np.random.normal(0,1,n) Y = np.random.normal(0,1,n) pl.scatter(X,Y)
點擊圖片查看答案。
提示:你須要當心文本對齊
從下面的代碼開始,試着從新生成這個圖片,添加紅柱的標籤。
n = 12 X = np.arange(n) Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) pl.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') pl.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') for x, y in zip(X, Y1): pl.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom') pl.ylim(-1.25, +1.25)
點擊圖片查看答案。
提示:你須要是使用clabel命令。
從下面的代碼開始,試着從新生成這個圖片,當心處理colormap (見下面的Colormaps)。
def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2) n = 256 x = np.linspace(-3, 3, n) y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') C = pl.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
點擊圖片查看答案。
提示:你須要當心處理在imshow命令中的圖像原點並使用colorbar
從下面的代碼開始,試着從新生成這個圖片,當心處理colormap和圖像插入以及原點。
def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) n = 10 x = np.linspace(-3, 3, 4 * n) y = np.linspace(-3, 3, 3 * n) X, Y = np.meshgrid(x, y) pl.imshow(f(X, Y))
點擊圖片查看答案。
提示:你須要調整Z。
從下面的代碼開始,試着從新生成這個圖片,當心處理顏色和切片大小。
Z = np.random.uniform(0, 1, 20) pl.pie(Z)
點擊圖片查看答案。
提示:你須要繪製兩次箭頭。
從下面的代碼開始,試着從新生成這個圖片,當心處理顏色和方向。
n = 8 X, Y = np.mgrid[0:n, 0:n] pl.quiver(X, Y)
點擊圖片查看答案。
從下面的代碼開始,試着從新生成這個圖片,當心處理線的樣式。
axes = pl.gca() axes.set_xlim(0, 4) axes.set_ylim(0, 3) axes.set_xticklabels([]) axes.set_yticklabels([])
點擊圖片查看答案。
提示:你能夠用不一樣的分割來使用多個子圖。
pl.subplot(2, 2, 1) pl.subplot(2, 2, 3) pl.subplot(2, 2, 4)
點擊圖片查看答案。
提示:你只須要修改axes
行。
從下面的代碼開始,試着從新生成這個圖片。
pl.axes([0, 0, 1, 1]) N = 20 theta = np.arange(0., 2 * np.pi, 2 * np.pi / N) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) bars = pl.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars): bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.5)
點擊圖片查看答案。
提示:你須要使用contourf
從下面的代碼開始,試着從新生成這個圖片。
from mpl_toolkits.mplot3d import Axes3D fig = pl.figure() ax = Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
點擊圖片查看答案。
更多請見:用Mayavi 3D繪圖
提示:看一下matplotlib標識
試着從0開始作這個事情!
點擊圖片查看答案。
快速閱讀
若是你想要快速看一下Scipy講座以便了解生態系統,你能夠直接跳到下一章:Scipy:高級科學計算。
本章的剩餘部分對理解其餘的介紹部分不是必須的。可是,請確保在稍後回來完成這個章節。
Matplotlib從大量的文檔以及用戶和開發者社區中收益匪淺。這裏是一些有趣的連接:
代碼都有很好的文檔,你能夠在Python會話中用特定命令很快的訪問:
In [3]:
import pylab as pl help(pl.plot)
Help on function plot in module matplotlib.pyplot: plot(*args, **kwargs) Plot lines and/or markers to the :class:`~matplotlib.axes.Axes`. *args* is a variable length argument, allowing for multiple *x*, *y* pairs with an optional format string. For example, each of the following is legal:: plot(x, y) # plot x and y using default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses If *x* and/or *y* is 2-dimensional, then the corresponding columns will be plotted. An arbitrary number of *x*, *y*, *fmt* groups can be specified, as in:: a.plot(x1, y1, 'g^', x2, y2, 'g-') Return value is a list of lines that were added. By default, each line is assigned a different color specified by a 'color cycle'. To change this behavior, you can edit the axes.color_cycle rcParam. The following format string characters are accepted to control the line style or marker: ================ =============================== character description ================ =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ``'.'`` point marker ``','`` pixel marker ``'o'`` circle marker ``'v'`` triangle_down marker ``'^'`` triangle_up marker ``'<'`` triangle_left marker ``'>'`` triangle_right marker ``'1'`` tri_down marker ``'2'`` tri_up marker ``'3'`` tri_left marker ``'4'`` tri_right marker ``'s'`` square marker ``'p'`` pentagon marker ``'*'`` star marker ``'h'`` hexagon1 marker ``'H'`` hexagon2 marker ``'+'`` plus marker ``'x'`` x marker ``'D'`` diamond marker ``'d'`` thin_diamond marker ``'|'`` vline marker ``'_'`` hline marker ================ =============================== The following color abbreviations are supported: ========== ======== character color ========== ======== 'b' blue 'g' green 'r' red 'c' cyan 'm' magenta 'y' yellow 'k' black 'w' white ========== ======== In addition, you can specify colors in many weird and wonderful ways, including full names (``'green'``), hex strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or grayscale intensities as a string (``'0.8'``). Of these, the string specifications can be used in place of a ``fmt`` group, but the tuple forms can be used only as ``kwargs``. Line styles and colors are combined in a single format string, as in ``'bo'`` for blue circles. The *kwargs* can be used to set line properties (any property that has a ``set_*`` method). You can use this to set a line label (for auto legends), linewidth, anitialising, marker face color, etc. Here is an example:: plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2) plot([1,2,3], [1,4,9], 'rs', label='line 2') axis([0, 4, 0, 10]) legend() If you make multiple lines with one plot command, the kwargs apply to all those lines, e.g.:: plot(x1, y1, x2, y2, antialised=False) Neither line will be antialiased. You do not need to use format strings, which are just abbreviations. All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with:: plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12). See :class:`~matplotlib.lines.Line2D` for details. The kwargs are :class:`~matplotlib.lines.Line2D` properties: agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False] antialiased or aa: [True | False] axes: an :class:`~matplotlib.axes.Axes` instance clip_box: a :class:`matplotlib.transforms.Bbox` instance clip_on: [True | False] clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] color or c: any matplotlib color contains: a callable function dash_capstyle: ['butt' | 'round' | 'projecting'] dash_joinstyle: ['miter' | 'round' | 'bevel'] dashes: sequence of on/off ink in points drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] figure: a :class:`matplotlib.figure.Figure` instance fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] gid: an id string label: string or anything printable with '%s' conversion. linestyle or ls: [``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``] linewidth or lw: float value in points lod: [True | False] marker: unknown markeredgecolor or mec: any matplotlib color markeredgewidth or mew: float value in points markerfacecolor or mfc: any matplotlib color markerfacecoloralt or mfcalt: any matplotlib color markersize or ms: float markevery: unknown path_effects: unknown picker: float distance in points or callable pick function ``fn(artist, event)`` pickradius: float distance in points rasterized: [True | False | None] sketch_params: unknown snap: unknown solid_capstyle: ['butt' | 'round' | 'projecting'] solid_joinstyle: ['miter' | 'round' | 'bevel'] transform: a :class:`matplotlib.transforms.Transform` instance url: a url string visible: [True | False] xdata: 1D array ydata: 1D array zorder: any number kwargs *scalex* and *scaley*, if defined, are passed on to :meth:`~matplotlib.axes.Axes.autoscale_view` to determine whether the *x* and *y* axes are autoscaled; the default is *True*. Additional kwargs: hold = [True|False] overrides default hold state
當你搜索如何提供一個特定圖片時,matplotlib畫廊也很是有用。每一個例子都有源碼。
這裏有一個小的畫廊。
最後,你能夠在用戶郵件列表尋求幫助,而開發者郵件列表則更偏技術。
這裏是一組表格,顯示了主要的屬性和樣式。
屬性 | 描述 | 外觀 |
---|---|---|
alpha (or a) | alpha 0-1範圍的透明度 | ![]() |
antialiased | True or False - use antialised rendering | ![]() ![]() |
color (or c) | matplotlib顏色參數 | ![]() |
linestyle (or ls) | see Line屬性 | |
linewidth (or lw) | 浮點, 線寬度用小數表示 | ![]() |
solid_capstyle | 實線頭的樣式 | ![]() |
solid_joinstyle | 實線的鏈接樣式 | ![]() |
dash_capstyle | 虛線頭的樣式 | ![]() |
dash_joinstyle | 虛線的鏈接樣式 | ![]() |
marker | see 標記 | |
markeredgewidth (mew) | 標記符號的線寬度 | ![]() |
markeredgecolor (mec) | 標記邊緣的顏色 | ![]() |
markerfacecolor (mfc) | 標記的填充顏色 | ![]() |
markersize (ms) | 標記的大小,以小數表示 | ![]() |
全部colormap均可以經過添加_r
來進行顏色反轉。例如gray_r
是gray
的補色。
若是你想要更多瞭解colormaps,檢查一下matplotlib colormaps的文檔