[英]Function numpy.reshape
我在matlab中有这个功能
cn = reshape (repmat (sn, n_rep, 1), 1, []);
没有带关键代码的python:
import numpy like np
from numpy.random import randint
M = 2
N = 2 * 10 ** 8 ### data value
n_rep = 3 ## number of repetitions
sn = randint (0, M, size = N) ### integers 0 and 1
print ("sn =", sn)
cn_repmat = np.tile (sn, n_rep)
print ("cn_repmat =", cn_repmat)
cn = np.reshape (cn_repmat, 1, [])
print (cn)
我不确定是否不知道复古血缘关系
File "C: / Users / Sergio Malhao / .spyder-py3 / Desktop / untitled6.py", line 17, under <module>
cn = np.reshape (cn_repmat, 1, [])
File "E: \ Anaconda3 \ lib \ site-packages \ numpy \ core \ fromnumeric.py", line 232, in reshape
return _wrapfunc (a, 'reshape', newshape, order = order)
File "E: \ Anaconda3 \ lib \ site-packages \ numpy \ core \ fromnumeric.py", line 57, in _wrapfunc
return getattr (obj, method) (* args, ** kwds)
ValueError: Can not reshape the array of size 600000000 in shape (1,)
Numpy 不应该是 1:1 的 matlab。 它的工作方式类似,但方式不同。 我假设您想将矩阵转换为一维数组。
尝试:
np.reshape (cn_repmat, (1, -1))
其中 (1, -1) 是定义新数组大小的元组。
一个形状维度可以是 -1。 在这种情况下,该值是从数组的长度和剩余维度推断出来的。
在八度:
>> sn = [0,1,2,3,4]
sn =
0 1 2 3 4
>> repmat(sn,4,1)
ans =
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
>> reshape(repmat(sn,4,1),1,[])
ans =
0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
在numpy
:
In [595]: sn=np.array([0,1,2,3,4])
In [596]: np.repeat(sn,4)
Out[596]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
In [597]: np.tile(sn,4)
Out[597]: array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
在 MATLAB 中矩阵至少是 2d; 在 numpy 中,它们可能是 1d。 Out[596]
是 1d。
我们可以通过制作sn
2d 来更接近 MATLAB:
In [608]: sn2 = sn[None,:] # = sn.reshape((1,-1))
In [609]: sn2
Out[609]: array([[0, 1, 2, 3, 4]])
In [610]: np.repeat(sn2,4,1)
Out[610]: array([[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]])
使用tile
我们必须转置或玩顺序游戏(MATLAB 是顺序 F):
In [613]: np.tile(sn,[4,1])
Out[613]:
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
In [614]: np.tile(sn,[4,1]).T.ravel()
Out[614]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
In [615]: np.tile(sn,[4,1]).ravel(order='F')
Out[615]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
ravel
相当于reshape(...., -1)
。 -1
函数,如 MATLAB 中的[]
整形时。
在numpy
repeat
是基本功能; tile
使用具有不同用户界面的repeat
(更像repmat
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.