使用numpys np.fromfunction评估Python lambda函数

fac*_*act 3 python numpy matrix multidimensional-array

设A1和A2为相同形状的numpy数组,比如说((d1,d2)).我想从它构建((d1,d1))数组,以便通过将函数应用于元组A1 [i],A2 [j]来定义其第[i,j]个条目.我在表单中使用np.fromfunction

f=lambda i,j: np.inner(A1[i],A2[j])
A=np.fromfunction(f, shape=(d1, d1)) 
Run Code Online (Sandbox Code Playgroud)

(以最快的方式建议使用函数给出的值初始化numpy数组).

但是我收到错误''IndexError:用作索引的数组必须是整数(或布尔)类型''.这很奇怪,因为例如将lambda函数更改为

 f=lambda i,j: i*j
Run Code Online (Sandbox Code Playgroud)

工作良好!似乎在lambda函数中调用另一个函数会导致麻烦

np.fromfunction
Run Code Online (Sandbox Code Playgroud)

(np.inner只是一个例子,我希望能够用其他类似的函数替换它).

unu*_*tbu 7

要调试的情况,提出f一个适当的功能,并添加一个print语句看到的价值ij:

import numpy as np
np.random.seed(2015)
d1, d2 = 5, 3
A1 = np.random.random((d1,d2))
A2 = np.random.random((d1,d2))
def f(i, j):
    print(i, j)
    return np.inner(A1[i],A2[j])
A = np.fromfunction(f, shape=(d1, d1)) 
Run Code Online (Sandbox Code Playgroud)

你会看到(i, j)平等:

(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.]]), 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.]]))
Run Code Online (Sandbox Code Playgroud)

啊哈.问题是这些数组是浮点值的.如错误消息所示,索引必须是整数或布尔类型.

仔细阅读docstring np.fromfunction显示它有第三个参数dtype,它控制坐标数组的数据类型:

Parameters
dtype : data-type, optional
    Data-type of the coordinate arrays passed to `function`.
    By default, `dtype` is float.
Run Code Online (Sandbox Code Playgroud)

因此解决方案是添加dtype=int到以下呼叫np.fromfunction:

A = np.fromfunction(f, shape=(d1, d1), dtype=int) 
Run Code Online (Sandbox Code Playgroud)