python中庫學習


一、numpy

NumPy的主要對象是同種元素的多維數組。這是一個所有的元素都是一種類型、通過一個正整數元組索引的元素表格(通常是元素是數字)。在NumPy中維度(dimensions)叫做軸(axes),軸的個數叫做秩(rank)。

例如,在3D空間一個點的坐標 [1, 2, 3] 是一個秩為1的數組,因為它只有一個軸。那個軸長度為3.又例如,在以下例子中,數組的秩為2(它有兩個維度).第一個維度長度為2,第二個維度長度為3.

[[ 1., 0., 0.],
 [ 0., 1., 2.]]

NumPy的數組類被稱作 ndarray 。通常被稱作數組。注意numpy.array和標准Python庫類array.array並不相同,后者只處理一維數組和提供少量功能。更多重要ndarray對象屬性有:

  • ndarray.ndim

    數組軸的個數,在python的世界中,軸的個數被稱作秩

  • ndarray.shape

    數組的維度。這是一個指示數組在每個維度上大小的整數元組。例如一個n排m列的矩陣,它的shape屬性將是(2,3),這個元組的長度顯然是秩,即維度或者ndim屬性

  • ndarray.size

    數組元素的總個數,等於shape屬性中元組元素的乘積。

  • ndarray.dtype

    一個用來描述數組中元素類型的對象,可以通過創造或指定dtype使用標准Python類型。另外NumPy提供它自己的數據類型。

  • ndarray.itemsize

    數組中每個元素的字節大小。例如,一個元素類型為float64的數組itemsiz屬性值為8(=64/8),又如,一個元素類型為complex32的數組item屬性為4(=32/8).

  • ndarray.data

    包含實際數組元素的緩沖區,通常我們不需要使用這個屬性,因為我們總是通過索引來使用數組中的元素。

>>> from numpy  import *
>>> a = arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int32'
>>> a.itemsize
4
>>> a.size
15
>>> type(a)
numpy.ndarray
>>> b = array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
numpy.ndarray

1、numpy.apply_along_axis

官方文檔給的:

numpy.apply_along_axis(func1daxisarr*args**kwargs)

Apply a function to 1-D slices along the given axis.

Execute func1d(a, *args) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.

Parameters:

func1d : function

This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

axis : integer

Axis along which arr is sliced.

arr : ndarray

Input array.

args : any

Additional arguments to func1d.

kwargs : any

Additional named arguments to func1d.

New in version 1.9.0.

Returns:

apply_along_axis : ndarray

The output array. The shape of outarr is identical to the shape of arr, except along the axisdimension. This axis is removed, and  replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar outarr will have one fewer dimensions than arr.

舉例:

>>> def my_func(a):#定義了一個my_func()函數,接受一個array的參數
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5 #返回array的第一個元素和最后一個元素的平均值
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) 
>>> np.apply_along_axis(my_func, 0, b)
array([ 4.,  5.,  6.])
>>> np.apply_along_axis(my_func, 1, b)
array([ 2.,  5.,  8.])

定義了一個my_func()函數,接受一個array的參數,然后返回array的第一個元素和最后一個元素的平均值,生成一個array:

1 2 3
4 5 6
7 8 9
np.apply_along_axis(my_func, 0, b)意思是說把b按列,傳給my_func,即求出的是矩陣列元素中第一個和最后一個的平均值,結果為;
4. 5. 6.
np.apply_along_axis(my_func, 1, b)意思是說把b按行,傳給my_func,即求出的是矩陣行元素中第一個和最后一個的平均值,結果為;
2. 5. 8.

 

參考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html

2、numpy.linalg.norm

  • (1)np.linalg.inv():矩陣求逆
  • (2)np.linalg.det():矩陣求行列式(標量)

np.linalg.norm

顧名思義,linalg=linear+algebranorm則表示范數,首先需要注意的是范數是對向量(或者矩陣)的度量,是一個標量(scalar)

首先help(np.linalg.norm)查看其文檔:

norm(x, ord=None, axis=None, keepdims=False)

這里我們只對常用設置進行說明,x表示要度量的向量,ord表示范數的種類,

 


>>> x = np.array([3, 4]) >>> np.linalg.norm(x) 5. >>> np.linalg.norm(x, ord=2) 5. >>> np.linalg.norm(x, ord=1) 7. >>> np.linalg.norm(x, ord=np.inf) 4

范數理論的一個小推論告訴我們:12

 

參考:http://blog.csdn.net/lanchunhui/article/details/51004387

3、numpy.expand_dims

主要是把array的維度擴大

numpy.expand_dims(aaxis)

舉例:

>>> x = np.array([1,2])
>>> x.shape
(2,)

shape是求矩陣形狀的。

 

>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)

維度擴大,axis=0

 

>>> y = np.expand_dims(x, axis=1)  # Equivalent to x[:,newaxis]
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)

維度擴大,axis=1

 4、numpy.transpose

 矩陣轉置操作。

numpy.transpose(aaxes=None)

Permute the dimensions of an array.

Parameters:

a : array_like

Input array.

axes : list of ints, optional

By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns:

p : ndarray

a with its axes permuted. A view is returned whenever possible.

舉例:

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])
>>> np.transpose(x)
array([[0, 2],
       [1, 3]])
>>> x=np.ones((1,2,3))
>>> x
array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]]])
>>> y=np.transpose(x,(1,0,2))
>>> y
array([[[ 1.,  1.,  1.]],

       [[ 1.,  1.,  1.]]])
>>> y.shape
(2, 1, 3)
>>> 

實際上就是把相應的坐標位置交換。

np.transpose(x,(1,0,2)) ,表示x中坐標的第一個和第二個要互換。比如
array([[[ 1.,  1.,  1.]], [[ 1., 1., 1.]]])中的加粗的1,它的位置是(1,0,1),轉換之后就變成了(1,0,2),把它從(1,0,1)這個位置,轉移到(1,0,2)

看的具體一點:
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> b
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> b.shape
(3, 3)
>>> c=np.transpose(b,(1,0))
>>> c
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
>>> 

這個操作依賴shape,實際上就是相應的坐標換位置,然后在從新放置元素。

 

 

二、skelearn 

1.pca

1.1、函數原型及參數說明

sklearn.decomposition.PCA(n_components=None, copy=True, whiten=False)


參數說明:
 
n_components:  
意義:PCA算法中所要保留的主成分個數n,也即保留下來的特征個數n
類型:int 或者 string,缺省時默認為None,所有成分被保留。
          賦值為int,比如n_components=1,將把原始數據降到一個維度。
          賦值為string,比如n_components='mle',將自動選取特征個數n,使得滿足所要求的方差百分比。

copy:

類型:bool,True或者False,缺省時默認為True。

意義:表示是否在運行算法時,將原始訓練數據復制一份。若為True,則運行PCA算法后,原始訓練數據的值不            會有任何改變,因為是在原始數據的副本上進行運算;若為False,則運行PCA算法后,原始訓練數據的              值會改,因為是在原始數據上進行降維計算。

whiten:

類型:bool,缺省時默認為False

意義:白化,使得每個特征具有相同的方差。關於“白化”,可參考:Ufldl教程

 

 

1.2、PCA對象的屬性

 
components_ :返回具有最大方差的成分。
explained_variance_ratio_:返回 所保留的n個成分各自的方差百分比。
n_components_:返回所保留的成分個數n。
mean_:
noise_variance_:
 
 

1.3、PCA對象的方法

  • fit(X,y=None)
fit()可以說是scikit-learn中通用的方法,每個需要訓練的算法都會有fit()方法,它其實就是算法中的“訓練”這一步驟。因為PCA是無監督學習算法,此處y自然等於None。
 
fit(X),表示用數據X來訓練PCA模型。
 
函數返回值:調用fit方法的對象本身。比如pca.fit(X),表示用X對pca這個對象進行訓練。
 
  • fit_transform(X)
用X來訓練PCA模型,同時返回降維后的數據。
newX=pca.fit_transform(X),newX就是降維后的數據。
 
  • inverse_transform()
將降維后的數據轉換成原始數據,X=pca.inverse_transform(newX)
 
  • transform(X)
將數據X轉換成降維后的數據。當模型訓練好后,對於新輸入的數據,都可以用transform方法來降維。
 
此外,還有get_covariance()、get_precision()、get_params(deep=True)、score(X, y=None)等方法,以后用到再補充吧。
 
 

1.4、example

 
以一組二維的數據data為例,data如下,一共12個樣本(x,y),其實就是分布在直線y=x上的點,並且聚集在x=1、2、3、4上,各3個。
>>> data
array([[ 1.  ,  1.  ],
       [ 0.9 ,  0.95],
       [ 1.01,  1.03],
       [ 2.  ,  2.  ],
       [ 2.03,  2.06],
       [ 1.98,  1.89],
       [ 3.  ,  3.  ],
       [ 3.03,  3.05],
       [ 2.89,  3.1 ],
       [ 4.  ,  4.  ],
       [ 4.06,  4.02],
       [ 3.97,  4.01]])

data這組數據,有兩個特征,因為兩個特征是近似相等的,所以用一個特征就能表示了,即可以降到一維。下面就來看看怎么用sklearn中的PCA算法包。
 
(1)n_components設置為1,copy默認為True,可以看到原始數據data並未改變,newData是一維的,並且明顯地將原始數據分成了四類。
 
>>> from sklearn.decomposition import PCA 
>>> pca=PCA(n_components=1)
>>> newData=pca.fit_transform(data)
>>> newData
array([[-2.12015916],
       [-2.22617682],
       [-2.09185561],
       [-0.70594692],
       [-0.64227841],
       [-0.79795758],
       [ 0.70826533],
       [ 0.76485312],
       [ 0.70139695],
       [ 2.12247757],
       [ 2.17900746],
       [ 2.10837406]])
>>> data
array([[ 1.  ,  1.  ],
       [ 0.9 ,  0.95],
       [ 1.01,  1.03],
       [ 2.  ,  2.  ],
       [ 2.03,  2.06],
       [ 1.98,  1.89],
       [ 3.  ,  3.  ],
       [ 3.03,  3.05],
       [ 2.89,  3.1 ],
       [ 4.  ,  4.  ],
       [ 4.06,  4.02],
       [ 3.97,  4.01]])

(2)將copy設置為False,原始數據data將發生改變。
>>> pca=PCA(n_components=1,copy=False)
>>> newData=pca.fit_transform(data)
>>> data
array([[-1.48916667, -1.50916667],
       [-1.58916667, -1.55916667],
       [-1.47916667, -1.47916667],
       [-0.48916667, -0.50916667],
       [-0.45916667, -0.44916667],
       [-0.50916667, -0.61916667],
       [ 0.51083333,  0.49083333],
       [ 0.54083333,  0.54083333],
       [ 0.40083333,  0.59083333],
       [ 1.51083333,  1.49083333],
       [ 1.57083333,  1.51083333],
       [ 1.48083333,  1.50083333]])


(3)n_components設置為'mle',看看效果,自動降到了1維。
>>> pca=PCA(n_components='mle')
>>> newData=pca.fit_transform(data)
>>> newData
array([[-2.12015916],
       [-2.22617682],
       [-2.09185561],
       [-0.70594692],
       [-0.64227841],
       [-0.79795758],
       [ 0.70826533],
       [ 0.76485312],
       [ 0.70139695],
       [ 2.12247757],
       [ 2.17900746],
       [ 2.10837406]])
 
(4)對象的屬性值
>>> pca.n_components
1
>>> pca.explained_variance_ratio_
array([ 0.99910873])
>>> pca.explained_variance_
array([ 2.55427003])
>>> pca.get_params
<bound method PCA.get_params of PCA(copy=True, n_components=1, whiten=False)>

我們所訓練的pca對象的n_components值為1,即保留1個特征,該特征的方差為2.55427003,占所有特征的方差百分比為0.99910873,意味着幾乎保留了所有的信息。get_params返回各個參數的值。
 
(5)對象的方法
>>> newA=pca.transform(A)
對新的數據A,用已訓練好的pca模型進行降維。
 
>>> pca.set_params(copy=False)
PCA(copy=False, n_components=1, whiten=False)
設置參數。

參考:http://doc.okbase.net/u012162613/archive/120946.html

2.svm

經常用到sklearn中的SVC函數,這里把文檔中的參數翻譯了一些,以備不時之需。

 

本身這個函數也是基於libsvm實現的,所以在參數設置上有很多相似的地方。(PS: libsvm中的二次規划問題的解決算法是SMO)。
sklearn.svm.SVC(C=1.0kernel='rbf'degree=3gamma='auto'coef0=0.0shrinking=Trueprobability=False,

tol=0.001cache_size=200class_weight=Noneverbose=Falsemax_iter=-1decision_function_shape=None,random_state=None)

參數:

 

l  C:C-SVC的懲罰參數C?默認值是1.0

C越大,相當於懲罰松弛變量,希望松弛變量接近0,即對誤分類的懲罰增大,趨向於對訓練集全分對的情況,這樣對訓練集測試時准確率很高,但泛化能力弱。C值小,對誤分類的懲罰減小,允許容錯,將他們當成噪聲點,泛化能力較強。

l  kernel :核函數,默認是rbf,可以是‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ 

    0 – 線性:u'v

    1 – 多項式:(gamma*u'*v + coef0)^degree

    2 – RBF函數:exp(-gamma|u-v|^2)

    3 –sigmoid:tanh(gamma*u'*v + coef0)

l  degree :多項式poly函數的維度,默認是3,選擇其他核函數時會被忽略。

l  gamma : ‘rbf’,‘poly’ 和‘sigmoid’的核函數參數。默認是’auto’,則會選擇1/n_features

l  coef0 :核函數的常數項。對於‘poly’和 ‘sigmoid’有用。

l  probability :是否采用概率估計?.默認為False

l  shrinking :是否采用shrinking heuristic方法,默認為true

l  tol :停止訓練的誤差值大小,默認為1e-3

l  cache_size :核函數cache緩存大小,默認為200

l  class_weight :類別的權重,字典形式傳遞。設置第幾類的參數C為weight*C(C-SVC中的C)

l  verbose :允許冗余輸出?

l  max_iter :最大迭代次數。-1為無限制。

l  decision_function_shape :‘ovo’, ‘ovr’ or None, default=None3

l  random_state :數據洗牌時的種子值,int值

主要調節的參數有:C、kernel、degree、gamma、coef0。

 

參考:http://blog.csdn.net/szlcw1/article/details/52336824


免責聲明!

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



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