python - 元组消耗 NumPy 数组的第一个单例维度
问题描述
给定一个 NumPy 数组:
array = np.random.randn(1,1,2)
print(array.shape)
# (1, 1, 2)
对其调用 tuple() 会吃掉第一个维度:
tupled_array = tuple(array)
print(tupled_array[0].shape)
# (1, 2) <- why?
我很好奇为什么?
如果我们用列表包装 NumPy 数组:
tupled_list_array = tuple([array])
print(tupled_list_array[0].shape)
# (1, 1, 2)
解决方案
tuple() 基于第一维提取元素。np.random.randn(1,1,2) 是一个 1x1x2 矩阵。tuple() 将其转换为以下元组: (1x2 matrix, )
另一方面,如果你使用 np.random.randn(2,1,1),tuple() 将它变成:(1x1 矩阵,1x1 矩阵)
推荐阅读
- laravel - Laravel 6 测试 - 未知数据库':内存:'
- sql - 如何确定 VBA SQL 语法问题的原因?
- java - 为什么 Java N1QL 中的 ORDER BY 不能按预期工作
- xamarin.forms - 如何添加单独的项目和类库的初始化
- visual-studio-code - 如何设置 Visual Studio Code 以运行和调试 ColdFusion 代码?
- python - docker中的张量流图像是否使用GPU?
- python - 如何在 scikit-learn 的基本情感分析中使用多个功能?
- xml - 如何从 XML 在 XSD 中声明名称
- python - 如何在我的嵌套字典中打印具有特定值的键?
- django - 使用 URLField 保存对象的正确方法