nump.expand_dims() 与 tensorflow.expand_dim() 函数的异同

本文探讨了numpy的expand_dims()与tensorflow的expand_dim()函数,两者都用于在原始数据上添加新的维度,但分别适用于array和tensor类型的数据。通过示例展示了各自的具体用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nump.expand_dims(array, axis),tensorflow.expand_dim(tensor, axis)

这两个expand_dims函数都是在原始数据的基础上,添加第axis维.

不同点在于处理的数据类型不同,前者是处理array类型的数据,后者是处理tensor类型的数据。

nump.expand_dims(array, axis) 用法

原始数据 

import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
print (x)
print (x.shape)
print ("x[0][1]: ",x[0][1])
[[1 2 3]
 [4 5 6]]
(2, 3)
x[0][1]:  2

扩展维度 

#在第0维添加1
y = np.expand_dims(x,axis=0)
print (y)
print ("y.shape: ",y.shape)
print ("y[0][1]: ",y[0][1])
print ("y[0][0][1]: ",y[0][0][1])
[[[1 2 3]
  [4 5 6]]]
y.shape:  (1, 2, 3)
y[0][1]:  [4 5 6]
y[0][0][1]:  2
#在第1维添加1
y = np.expand_dims(x,axis=1)
print (y)
print ("y.shape: ",y.shape)
print ("y[1][0]: ",y[1][0])
print ("y[0][0][1]: ",y[0][0][1])
[[[1 2 3]]

 [[4 5 6]]]
y.shape:  (2, 1, 3)
y[1][0]:  [4 5 6]
y[0][0][1]:  2
#在第3维添加1
y = np.expand_dims(x,axis=2)
print (y)
print ("y.shape: ",y.shape)
print ("y[1][0]: ",y[1][0])
print ("y[0][1][0]: ",y[0][1][0])
[[[1]
  [2]
  [3]]

 [[4]
  [5]
  [6]]]
y.shape:  (2, 3, 1)
y[1][0]:  [4]
y[0][1][0]:  2

tensorflow.expand_dim(tensor, axis) 用法 

原始数据

import tensorflow as tf
x = tf.Variable([[1, 2, 3], [4, 5, 6]])
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    value = sess.run(x)
    print (value)
    print (x.shape)
    print ("x[0][1]: ",value[0][1])

 

[[1 2 3]
 [4 5 6]]
(2, 3)
x[0][1]:  2

扩展维度

#在第0维添加1
y = tf.expand_dims(x,axis=0)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    value = sess.run(y)
    print (value)
    print (y.shape)
    print ("y[0][1]: ",value[0][1])

 

[[[1 2 3]
  [4 5 6]]]
(1, 2, 3)
y[0][1]:  [4 5 6]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值