首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向现有np数组中添加维度

向现有np数组中添加维度
EN

Stack Overflow用户
提问于 2021-02-12 19:59:14
回答 1查看 41关注 0票数 1

我试图用经典的线性代数把数字数组中的维数和矩阵的维数联系起来。假设以下内容:

代码语言:javascript
复制
In [1]  import numpy as np
In [2]  rand = np.random.RandomState(42)
In [3]  a = rand.rand(3,2)
In [4]  a
Out[4]:
array([[0.61185289, 0.13949386],
       [0.29214465, 0.36636184],
       [0.45606998, 0.78517596]])
In [5]: a[np.newaxis,:,:]
Out[5]:
array([[[0.61185289, 0.13949386],
        [0.29214465, 0.36636184],
        [0.45606998, 0.78517596]]])
In [6]: a[:,np.newaxis,:]
Out[6]:
array([[[0.61185289, 0.13949386]],

       [[0.29214465, 0.36636184]],

       [[0.45606998, 0.78517596]]])

In [7]: a[:,:,np.newaxis]
Out[7]:
array([[[0.61185289],
        [0.13949386]],

       [[0.29214465],
        [0.36636184]],

       [[0.45606998],
        [0.78517596]]])

我的问题如下:

  1. a的尺寸是3X2是正确的吗?换句话说,一个3X2矩阵?
  2. a[np.newaxis,:,:]的尺寸是1×3×2,这是正确的吗?换句话说,包含3X2矩阵的矩阵?
  3. a[:,np.newaxis,:]的尺寸是3×1×2,这是正确的吗?换句话说,包含31X2矩阵的矩阵?
  4. a[:,:,np.newaxis]的尺寸是3×2 X1,这是正确的吗?换句话说,一个矩阵包含3个矩阵,每个矩阵包含21X1矩阵?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-12 20:16:55

  1. 三个2x1矩阵,每个矩阵包含一个大小为1的向量

只要找到使用.shape的方法

代码语言:javascript
复制
import numpy as np

rand = np.random.RandomState(42)

# 1.
a = rand.rand(3, 2)
print(a.shape, a, sep='\n', end='\n\n')

# 2.
b = a[np.newaxis, :, :]
print(b.shape, b, sep='\n', end='\n\n')

# 3.
c = a[:, np.newaxis, :]
print(c.shape, c, sep='\n', end='\n\n')

# 4.a
d = a[:, :, np.newaxis]
print(d.shape, d, sep='\n', end='\n\n')

# 4.b
print(d[0].shape, d[0], sep='\n', end='\n\n')
print(d[0, 0].shape, d[0, 0])

产出:

代码语言:javascript
复制
(3, 2)
[[0.37454012 0.95071431]
 [0.73199394 0.59865848]
 [0.15601864 0.15599452]]

(1, 3, 2)
[[[0.37454012 0.95071431]
  [0.73199394 0.59865848]
  [0.15601864 0.15599452]]]

(3, 1, 2)
[[[0.37454012 0.95071431]]

 [[0.73199394 0.59865848]]

 [[0.15601864 0.15599452]]]

(3, 2, 1)
[[[0.37454012]
  [0.95071431]]

 [[0.73199394]
  [0.59865848]]

 [[0.15601864]
  [0.15599452]]]

(2, 1)
[[0.37454012]
 [0.95071431]]

(1,) [0.37454012]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66178328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档