如何与QUOT;规模"一个numpy的阵列? [英] How to "scale" a numpy array?
问题描述
我想通过n的因子缩放形状的阵列(H; W),因此,形状的阵列(H * N,W * n)时,与
说,我有一个2x2的阵列:
阵列([1,1]
[0,1]])
我想扩展阵列,成为4×4:
阵列([1,1,1,1]
[1,1,1,1],
[0,0,1,1],
[0,0,1,1]])
也就是说,原来的阵列中的每个单元的值被复制到4对应的细胞所得到的数组中为止。假设任意数组的大小和比例因子,什么是做到这一点的最有效方法是什么?
您应该使用 Kronecker积,<一个HREF =http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html> numpy.kron :
计算Kronecker积,取得由第一缩放第二阵列块构成的复合阵列
块引用>导入numpy的是NP
一个= np.array([1,1],
[0,1]])
N = 2
np.kron(一,np.ones((N,N)))这给你想要什么:
阵列([1,1,1,1]
[1,1,1,1],
[0,0,1,1],
[0,0,1,1]])I would like to scale an array of shape (h, w) by a factor of n, resulting in an array of shape (h*n, w*n), with the.
Say that I have a 2x2 array:
array([[1, 1], [0, 1]])
I would like to scale the array to become 4x4:
array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])
That is, the value of each cell in the original array is copied into 4 corresponding cells in the resulting array. Assuming arbitrary array size and scaling factor, what's the most efficient way to do this?
解决方案You should use the Kronecker product, numpy.kron:
Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first
import numpy as np a = np.array([[1, 1], [0, 1]]) n = 2 np.kron(a, np.ones((n,n)))
which gives what you want:
array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])
这篇关于如何与QUOT;规模&QUOT;一个numpy的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!