python中的numpy函数算相关系数_NumPy ufunc通用函数
NumPy 提供了兩種基本的對象,即 ndarray 和 ufunc 對象。前面幾節已經介紹了 ndarray,本節將介紹 Numpy。ufunc 是 universal function 的縮寫,意思是“通用函數”,它是一種能對數組的每個元素進行操作的函數。
許多 ufunc 函數都是用C語言級別實現的,因此它們的計算速度非常快。
此外,ufun 比 math 模塊中的函數更靈活。math 模塊的輸入一般是標量,但 NumPy 中的函數可以是向量或矩陣,而利用向量或矩陣可以避免使用循環語句,這點在機器學習、深度學習中非常重要。
表1:NumPy 中的幾個常用通用函數
函數
使用方法
sqrt()
計算序列化數據的平方根
sin()、cos()
三角函數
abs()
計算序列化數據的絕對值
dot()
矩陣運算
log()、logl()、log2()
對數函數
exp()
指數函數
cumsum()、cumproduct()
累計求和、求積
sum()
對一個序列化數據進行求和
mean()
計算均值
median()
計算中位數
std()
計算標準差
var()
計算方差
corrcoef()
計算相關系數
math 與 numpy 函數的性能比較
請看下面的代碼:
import time
import math
import numpy as np
x = [i * 0.001 for i in np.arange(1000000)]
start = time.clock()
for i, t in enumerate(x):
x[i] = math.sin(t)
print ("math.sin:", time.clock() - start )
x = [i * 0.001 for i in np.arange(1000000)]
x = np.array(x)
start = time.clock()
np.sin(x)
print ("numpy.sin:", time.clock() - start )
打印結果:
math.sin: 0.5169950000000005
numpy.sin: 0.05381199999999886
由此可見,numpy.sin 比 math.sin 快近 10 倍。
循環與向量運算比較
充分使用 Python 的 NumPy 庫中的內建函數(Built-in Function),來實現計算的向量化,可大大地提高運行速度。NumPy 庫中的內建函數使用了 SIMD 指令。如下使用的向量化要比使用循環計算速度快得多。如果使用 GPU,其性能將更強大,不過 Numpy 不支持 GPU。
請看下面的代碼:
import time
import numpy as np
x1 = np.random.rand(1000000)
x2 = np.random.rand(1000000)
##使用循環計算向量點積
tic = time.process_time()
dot = 0
for i in range(len(x1)):
dot+= x1[i]*x2[i]
toc = time.process_time()
print ("dot = " + str(dot) + "\n for loop----- Computation time = " + str(1000*(toc - tic)) + "ms")
##使用numpy函數求點積
tic = time.process_time()
dot = 0
dot = np.dot(x1,x2)
toc = time.process_time()
print ("dot = " + str(dot) + "\n verctor version---- Computation time = " + str(1000*(toc - tic)) + "ms")
輸出結果:
dot = 250215.601995
for loop----- Computation time = 798.3389819999998ms
dot = 250215.601995
verctor version---- Computation time = 1.885051999999554ms
從運行結果上來看,使用 for 循環的運行時間大約是向量運算的 400 倍。因此,在深度學習算法中,一般都使用向量化矩陣進行運算。
總結
以上是生活随笔為你收集整理的python中的numpy函数算相关系数_NumPy ufunc通用函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python元祖迭代_如何在Python
- 下一篇: 竣工验收备案表长什么样(竣工验收备案表的