环境: tensorfow 2.*
def concatenate(inputs, axis=-1, **kwargs):
axis=n表示从第n个维度进行拼接,对于一个三维矩阵,axis的取值可以为[-3, -2, -1, 0, 1, 2]。
维度说明下图,0在深度,1在行,2在列
代码
import numpy as np
import tensorflow as tf
t1 = tf.Variable(np.array([[[1, 2], [2, 3]], [[4, 4], [5, 3]]]))
t2 = tf.Variable(np.array([[[7, 4], [8, 4]], [[2, 10], [15, 11]]]))
d0 = tf.keras.layers.concatenate([t1, t2], axis=0)
d1 = tf.keras.layers.concatenate([t1, t2], axis=1)
d2 = tf.keras.layers.concatenate([t1, t2], axis=2)
d3 = tf.keras.layers.concatenate([t1, t2], axis=-1)
print(d0)
print(d1)
print(d2)
print(d3)
输出
tf.Tensor(
[[[ 1 2]
[ 2 3]]
[[ 4 4]
[ 5 3]]
[[ 7 4]
[ 8 4]]
[[ 2 10]
[15 11]]], shape=(4, 2, 2), dtype=int32) # 4代表深度,类似4页
tf.Tensor(
[[[ 1 2]
[ 2 3]
[ 7 4]
[ 8 4]]
[[ 4 4]
[ 5 3]
[ 2 10]
[15 11]]], shape=(2, 4, 2), dtype=int32)
tf.Tensor(
[[[ 1 2 7 4]
[ 2 3 8 4]]
[[ 4 4 2 10]
[ 5 3 15 11]]], shape=(2, 2, 4), dtype=int32)
tf.Tensor(
[[[ 1 2 7 4]
[ 2 3 8 4]]
[[ 4 4 2 10]
[ 5 3 15 11]]], shape=(2, 2, 4), dtype=int32)
Process finished with exit code 0
数组维度
数组的常用函数
print(np.arange(0,7,1,dtype=np.int16)) # 0为起点,间隔为1时可缺省(引起歧义下不可缺省)
print(np.ones((2,3,4),dtype=np.int16)) # 2页,3行,4列,全1,指定数据类型
print(np.zeros((2,3,4))) # 2页,3行,4列,全0
print(np.empty((2,3))) #值取决于内存
print(np.arange(0,10,2)) # 起点为0,不超过10,步长为2
print(np.linspace(-1,2,5)) # 起点为-1,终点为2,取5个点
print(np.random.randint(0,3,(2,3))) # 大于等于0,小于3,2行3列的随机整数
输出
[0 1 2 3 4 5 6]
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
[[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]]
[[ 1.39069238e-309 1.39069238e-309 1.39069238e-309]
[ 1.39069238e-309 1.39069238e-309 1.39069238e-309]]
[0 2 4 6 8]
[-1. -0.25 0.5 1.25 2. ]
[[1 0 1]
[0 1 0]]