最近学机器学习的时候,看到这样一段代码:x.reshape(-1,1),一直搞不懂参数-1是什么意思。最后就去看了看官方文档:
我们主要看一下红框框里面的内容:
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
翻译:
新形状应与原形状兼容。如果是整数,那么结果将是该长度的1-D数组。一个形状维数可以是-1,该值是从数组的长度和其余维数推断出来的。
人话:
这里我们用一个例子来说明,假如一个数组的shape是(3,4),这里3*4=12,对这个数组进行reshape操作后,新数组的shape中各维度的乘积也应为12。如果其中一个参数是-1,另一个参数是2,也就是(-1,2),那么这个新数组的shape就是(12/2,2),即(6,2);如果另一个参数是1,那么这个新数组的shape就是(12/1,1),即(12,1).
更多的情况用下面的代码实现:

本文通过实例解析了numpy库中reshape函数参数-1的意义,即如何在保持元素总数不变的情况下,通过设置未知维度为-1来自适应调整数组形状。
3万+

被折叠的 条评论
为什么被折叠?



