为什么我们需要np

为什么我们需要np

本文介绍了为什么我们需要np.squeeze()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,数组会用np.squeeze()压缩.在文档中,它说

Very often, arrays are squeezed with np.squeeze(). In the documentation, it says

但是我仍然想知道:为什么 呈a形状的零维和无量纲条目?或者换句话说:为什么a.shape = (2,1) (2,)同时存在?

However I'm still wondering: Why are zero and nondimensional entries in the shape of a? Or to put it differently: Why do both a.shape = (2,1) and (2,) exist?

推荐答案

除了这两件事之间的数学差异之外,还有可预测性的问题.如果遵循您的建议,那么您绝对不会依赖数组的维数.因此,任何形式为my_array[x,y]的表达式都需要替换为首先检查my_array是否实际上是二维的并且在某个时候没有隐式squeeze的东西.与偶尔做明确说明的squeeze混淆相比,这可能会使代码混淆得多.

Besides the mathematical differences between the two things, there is the issue of predictability. If your suggestion was followed, you could at no point rely on the dimension of your array. So any expression of the form my_array[x,y] would need to be replaced by something that first checks if my_array is actually two-dimensional and did not have an implicit squeeze at some point. This would probably obfuscate code far more than the occasional squeeze, which does a clearly specified thing.

实际上,可能甚至很难说出哪个轴已被移走,从而导致大量新问题.

Actually, it might even be very hard to tell, which axis has been removed, leading to a whole host of new problems.

本着 Python的禅宗的精神,Explicit is better than implicit ,我们也可以说,我们更喜欢显式squeeze而不是隐式数组转换.

In the spirit of The Zen of Python, also Explicit is better than implicit, we can also say that we should prefer explicit squeeze to implicit array conversion.

这篇关于为什么我们需要np.squeeze()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:42