python在數據處理中常用的模塊之numpy


一 numpy模塊

NumPy系統是Python的一種開源的數值計算擴展。這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表(nested list structure)結構要高效的多(該結構也可以用來表示矩陣(matrix))。

import numpy as np

(1).np.linalg.norm(x)    

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

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

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

 x表示要度量的向量,ord表示范數的種類

參數 說明 計算方法
默認 二范數 np.sqrt(x1**2+x2**2+....+xn**2)
ord=2 二范數 同上
ord=1 一范數 |x1|+|x2|+...+|xn|
ord=np.inf 無窮范數 max(|xi|)

 

  用於計算向量x的2范數

x = np.array([3,4])
y = np.linalg.norm(x)
print(y)

   輸出結果為5.0

   計算矩陣x的2范數  對矩陣每一個元素求平方和然后開根號

x = np.array([3,4,5],[3,4,5])
y = np.linalg.norm(x)
print(x)

   輸出結果為10.0

(2).np.log10(x)              #計算以10為底的對數

    np.log(x)                       #log下什么都不寫默認是自然對數 e為底

x1 = 10
y1 = np.log10(x1)
x2 = np.e
y2 = np.log(x2)
print(y1,y2)

   輸出結果為1.0 1.0

 (3).np.nan_to_num:Replace nan with zero and inf with finite numbers.
      把np.nan(非常小的數字,接近0)用0取代
       np.inf,或者-np.inf(正負無窮大的數字)用有限數替代

np.set_printoptions(precision=8)
x = np.array([np.inf, -np.inf, np.nan, -128, 128])
print(np.nan_to_num(x))

     輸出結果為[  1.79769313e+308  -1.79769313e+308   0.00000000e+000  -1.28000000e+002
     1.28000000e+002]

(4).numpy.random.randn(d0, d1, …, dn)是從標准正態分布中返回一個或多個樣本值。
      numpy.random.rand(d0, d1, …, dn)的隨機樣本位於[0, 1)中。

x1 = np.random.randn(2,4)
print(x1)
x2 = np.random.rand(2,4)
print(x2)

    輸出結果 

  [[-1.47942602  0.10728309 -1.49062996  1.32908036]
   [ 0.37065869 -0.04594328  0.72822393  0.74898655]]
  [[ 0.54672608  0.0216933   0.04434537  0.65831692]
   [ 0.06332446  0.75230353  0.12993006  0.75911764]]

(5). numpy.random.normal(loc=0.0, scale=1.0, size=None)   正太分布

      參數的意義為:

  loc:float 概率分布的均值,對應着整個分布的中心center

  scale:float 概率分布的標准差,對應於分布的寬度,scale越大越矮胖,scale越小,越瘦高

  size:int or tuple of ints  維數

(6).numpy.random.random(size)

random.random()用於生成一個0到1的隨機符點數: 0 <= n < 1.0

(7).numpy.random.uniform(a,b)
       用於生成一個指定范圍內的隨機符點數,兩個參數其中一個是上限,一個是下限。如果a > b,則生成的隨機數n: a <= n <= b。如果 a <b, 則 b <= n <= a

print random.uniform(10, 20)
print random.uniform(20, 10)
# 18.7356606526
# 12.5798298022  

(8).random.randint(a, b)

用於生成一個指定范圍內的整數。其中參數a是下限,參數b是上限,生成的隨機數n: a <= n <= b

print random.randint(12, 20)  # 生成的隨機數 n: 12 <= n <= 20
print random.randint(20, 20)  # 結果永遠是20     
# print random.randint(20, 10)  # 該語句是錯誤的。下限必須小於上限

(9).random.randrange([start], stop[, step])

從指定范圍內,按指定基數遞增的集合中 獲取一個隨機數。如:random.randrange(10, 100, 2),結果相當於從[10, 12, 14, 16, ... 96, 98]序列中獲取一個隨機數。random.randrange(10, 100, 2)在結果上與 random.choice(range(10, 100, 2) 等效.

(10).andom.choice(sequence)

從序列中獲取一個隨機元素。其函數原型為:random.choice(sequence)。參數sequence表示一個有序類型。這里要說明 一下:sequence在python不是一種特定的類型,而是泛指一系列的類型。list, tuple, 字符串都屬於sequence。有關sequence可以查看python手冊數據模型這一章。下面是使用choice的一些例子:

print random.choice("學習Python")
print random.choice(["JGood", "is", "a", "handsome", "boy"])
print random.choice(("Tuple", "List", "Dict"))  

(11).random.shuffle(x[, random])

用於將一個列表中的元素打亂。如:

p = ["Python", "is", "powerful", "simple", "and so on..."]
random.shuffle(p)
print p
# ['powerful', 'simple', 'is', 'Python', 'and so on...']  

(12)對ndarray類型使用len函數

len用於獲取一個數組的長度,如果是多維數組,則獲取數組的行數。

    temp = np.zeros(shape=[10,20])
    print(len(temp))  #10

 

(13)np.squeeze(a, axis=None):

從數組的形狀中刪除單維度條目,即把shape中為1的維度去掉。

    x = np.array([[[0], [1], [2]]])
    print(x.shape)  #(1, 3, 1)
    print(np.squeeze(x).shape)     #(3,)
    print(np.squeeze(x, axis=(2,)).shape) #    (1, 3)

 

(14).  np.expand_dims(a, axis):

該函數和np.squeeze()正好相反,數組形狀擴充一個維度的。

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

 

 (15)列向量和行向量,以及秩為1的數組的區別

# -*- coding: utf-8 -*-
"""
Created on Sun Mar 25 20:17:21 2018
    x = np.array([[[0], [1], [2]]])
    print(x.shape)  #(1, 3, 1)
    print(np.squeeze(x).shape)     #(3,)
    print(np.squeeze(x, axis=(2,)).shape) #    (1, 3)
 
         

 


@author: Administrator
"""

import numpy as np

'''
下面顯示了秩為1的數組以及列向量和行向量的使用,以及區別.我們在使用的時候最好不要使用秩為1的數組
並且當我們不確定矩陣或者向量的維數維數時,我們可以使用.reshape(m,n)指定
'''

#a為秩為1的數組,我們可以看到轉置和本身一致,shape都是(5,)
a = np.random.randn(5)
print(a,a.shape)       #[ 0.58371745  0.62467384  0.72225761 -0.32777546 -1.06321595] (5,)
print(a.T,a.T.shape)   #[ 0.58371745  0.62467384  0.72225761 -0.32777546 -1.06321595] (5,)

r = np.dot(a,a)
print(r,r.shape)   #2.49046445333 ()


r = np.dot(a,a.T)
print(r,r.shape)   #2.49046445333 ()


#a1為5x1的列向量
a1 = np.random.randn(5,1)
print(a1,a1.shape)   #[[-0.20126605]
                     # [-0.08183096]
                     # [ 0.12709234]
                     # [ 1.88915869]
                     # [1.18566033]] (5, 1)   

#r1 = np.dot(a1,a1)   #會報錯   shapes (5,1) and (5,1) not aligned: 1 (dim 1) != 5 (dim 0)
#print(r1,r1.shape)


r1 = np.dot(a1,a1.T)
print(r1,r1.shape)   #[[ 0.04050802  0.01646979 -0.02557937 -0.3802235  -0.23863317]
                     # [ 0.01646979  0.00669631 -0.01040009 -0.15459166 -0.09702372]
                     # [-0.02557937 -0.01040009  0.01615246  0.24009759  0.15068834]
                     # [-0.3802235  -0.15459166  0.24009759  3.56892057  2.23990052]
                     # [-0.23863317 -0.09702372  0.15068834  2.23990052  1.40579042]] (5, 5) 

#a2為1x5的行向量
a2 = np.random.randn(1,5)
print(a2,a2.shape)   #[ 0.48272148  0.4743339  -0.31309436  2.01153588 -0.58482391] (5,) 

#r2 = np.dot(a2,a2)   #會報錯   shapes (1,5) and (,5) not aligned: 5 (dim 5) != 1 (dim 0)
#print(r2,r2.shape)


r2= np.dot(a2,a2.T)
print(r2,r2.shape)    #[[ 3.81502768]] (1, 1)


#由list或者touple轉換為的秩為數組,我們最好指定其shape
c = np.array([1,2,3,4])
print(c.shape)      #(4,)

c = np.array([1,2,3,4]).reshape(4,1)
print(c.shape)      #(4,1)

d = np.array([[1,2,3],[4,5,6]])
print(d.shape)     #(2,3)

參考文獻

[1]Python3.1-標准庫之Numpy


免責聲明!

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



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