機器學習---筆記----numpy和math包中的常用函數


本文只是簡單羅列一下再機器學習過程中遇到的常用的數學函數。

1. math.fabs(x): 返回x的絕對值。同numpy。

>>> import numpy
>>> import math
>>> numpy.fabs(-5)
5.0
>>> math.fabs(-5)
5.0
View Code

2.  x.astype(type): 返回type類型的x, type 一般可以為numpy.int, numpy.float等,沒有math.int等。

>>> import numpy as np
>>> d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.float)
>>> f=d.astype(np.int)
>>> print f
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
>>> d
array([[  1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.],
       [  9.,  10.,  11.,  12.]])
View Code

3. numpy.frompyfunc(func, para_size, valu_size): 將一個計算單個元素的函數func 轉換成計算能計算多個元素的函數,返回類型為object。

>>> f=np.frompyfunc(np.fabs, 1,1)
>>> f([-1,-2,-3,-4])
array([1.0, 2.0, 3.0, 4.0], dtype=object)
View Code

4. numpy.zeros_like(x): 返回一個用0填充的跟輸入數組形 x 狀和類型一樣的數組。類似的還有 np.ones_like(), np.empty_like(), math包沒有該函數。

>>> d
array([[  1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.],
       [  9.,  10.,  11.,  12.]])
>>> np.zeros_like(d)
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.empty_like(d)
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones_like(d)
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
View Code

5. numpy.exp(x): 返回e的x次方, math函數同此。

>>> np.exp(2)
7.3890560989306504
>>> math.exp(2)
7.38905609893065
View Code

6. numpy.sqrt(x): 返回x的平方根, math函數同此。

>>> math.exp(2)
7.38905609893065
>>> math.sqrt(2)
1.4142135623730951
>>> numpy.sqrt(2)
1.4142135623730951
>>> numpy.sqrt(4)
2.0
View Code

7. numpy.e, numpy.pi: 引用e, pi, math函數同此。

>>> np.e
2.718281828459045
>>> np.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.pi
3.141592653589793
View Code

 


免責聲明!

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



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