如何“扩展"一个numpy数组? [英] How to "scale" a numpy array?
问题描述
我想将一个形状为 (h, w) 的数组缩放 n 倍,从而得到一个形状为 (h*n, w*n) 的数组.
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.
假设我有一个 2x2 数组:
Say that I have a 2x2 array:
array([[1, 1],
[0, 1]])
我想将数组缩放为 4x4:
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]])
即,将原始数组中每个单元格的值复制到结果数组中的 4 个对应单元格中.假设任意数组大小和缩放因子,最有效的方法是什么?
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?
推荐答案
您应该使用 Kronecker 产品, numpy.kron:
计算 Kronecker 乘积,一个由第二个数组的块组成的复合数组,由第一个缩放
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)))
提供你想要的:
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1]])
这篇关于如何“扩展"一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!