简体   繁体   English

如何理解ndarray.reshape函数?

[英]How to understand ndarray.reshape function?

The prototype of reshape() is that reshape(shape, order="C") , and the type of shape is tuple. reshape()的原型是reshape(shape, order="C") ,并且形状的类型是元组。 So we should call this function with myarray.reshape((1000, 1, 32, 32)) , But I find that many use myarray.reshape(1000, 1, 32, 32) , why? 因此,我们应该使用myarray.reshape((1000, 1, 32, 32))调用此函数,但是我发现很多人都使用myarray.reshape(1000, 1, 32, 32) ,为什么呢?

It's a bit of hidden flexibility built into the reshape method. reshape方法内置了一些隐藏的灵活性。

The keyword here needs to be explicit: you can't do for example: 此处的关键字必须明确:您不能这样做:

myarray.reshape(1000, 1, 32, 32, "C")

You'll get a TypeError , saying that an integer is required. 您将得到一个TypeError ,说必须是一个整数。

(In fact, even using a tuple: (实际上,即使使用元组:

myarray.reshape((1000, 1, 32, 32), "C")

raises the TypeError .) 引发TypeError 。)

If you look at the source code (eg, at GitHub , you'll see that, after the keywords are parsed, there is a check for 0 or 1 arguments. In that case, the argument is interpreted as a tuple. If there are more arguments, each is interpreted as an integer and combined into a tuple as the new shape (the keyword arguments have already been taken out). 如果查看源代码(例如,在GitHub上 ,您会看到,在解析关键字之后,将检查0或1个参数。在这种情况下,该参数被解释为元组。更多参数,每个参数都将解释为整数,并组合成新形状的元组(关键字参数已被取出)。


As to which one you should use: I guess there's not really a good answer. 关于应该使用哪一个:我想这不是一个很好的答案。
You could stick with the documentation, and use tuples. 您可以坚持使用文档,并使用元组。
The multiple-integer-arguments convention, however, feels rather obvious. 但是,多整数参数约定相当明显。

Do stick to the convention that you, or the project you're working on, use(s). 请遵守您或您正在从事的项目使用的约定。 Don't use tuples and individual integer arguments in the same project. 不要在同一项目中使用元组和单个整数参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM