numpy函數fromfunction分析


    從函數規則創建數組是非常方便的方法。在numpy中我們常用fromfunction函數來實現這個功能。

    在numpy的官網有這么一個例子。

 1 >>> def f(x,y):
 2 ...         return 10*x+y
 3 ...
 4 >>> b = fromfunction(f,(5,4),dtype=int)
 5 >>> b
 6 array([[ 0,  1,  2,  3],
 7        [10, 11, 12, 13],
 8        [20, 21, 22, 23],
 9        [30, 31, 32, 33],
10        [40, 41, 42, 43]])

      查找help()解釋如下:

  numpy.fromfunction(functionshape**kwargs)[source]

Construct an array by executing a function over each coordinate.

The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).

Parameters:

function : callable

The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters in turn be (0, 0), (0, 1), (1, 0), (1, 1).

shape : (N,) tuple of ints

Shape of the output array, which also determines the shape of the coordinate arrays passed to function.

dtype : data-type, optional

Data-type of the coordinate arrays passed to function. By default, dtype is float.

Returns:

fromfunction : any

The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would match the shape parameter.

 

    主要是第二個參數shape,(N,)定義了fromfunction的輸出數據形式。

    說起來比較繞口,下面用幾個例子說明。

     

 1 # -*- coding: utf-8 -*-
 2 from numpy import *
 3 
 4 def f1(x,y):
 5     return x
 6 
 7 def f2(x,y):
 8     return y   
 9 
10 def f3(x,y):
11     return 2*x+y

  運行測試:

>>> b=fromfunction(f1, (5,5), dtype = int)
>>> b
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])

>>> b=fromfunction(f1, (5,4), dtype = int)
>>> b
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]])

>>> b=fromfunction(f2, (5,5), dtype = int)
>>> b
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
>>> b=fromfunction(f3, (5,5), dtype = int)
>>> b
array([[ 0, 1, 2, 3, 4],
[ 2, 3, 4, 5, 6],
[ 4, 5, 6, 7, 8],
[ 6, 7, 8, 9, 10],
[ 8, 9, 10, 11, 12]])
>>>

  從上面的測試可以看出,shape()定義了輸出矩陣的大小。如shape(5,4),則x參數是5行1列行列式[0,1,2,3,4]. y參數1行4列行列式[0,1,2,3]. 

      將x,y帶人func函數計算,最后結果的每個元素是根據func 函數來計算得出。

 


免責聲明!

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



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