Python多维数组堆叠咨询:合并数组及动态追加实现方法
Hey there! Let's break down your questions step by step—you're absolutely on the right track using the term "stacking" for this kind of array operation in TensorFlow. Here's how to tackle each part:
To combine two (28,28,1) tensors into a single tensor with a new leading dimension (making it (2,28,28,1)), use tf.stack(). This function creates a new dimension and stacks the input tensors along it:
import tensorflow as tf # Example tensors matching your shapes A = tf.random.normal((28, 28, 1)) B = tf.random.normal((28, 28, 1)) # Stack along axis 0 (the new leading dimension) C = tf.stack([A, B], axis=0) print(C.shape) # Output: (2, 28, 28, 1)
The axis=0 parameter tells TensorFlow to add the new dimension at the start—exactly what you need here.
TensorFlow tensors are immutable by default, so you can't modify them in-place like a Python list with +=. But there are two easy ways to achieve the same effect:
Option 1: Use tf.concat() for one-off appends
First, expand the new tensor's dimensions to match the stack's shape (add a leading 1 dimension), then concatenate along the existing leading axis:
# New (28,28,1) tensor to append D = tf.random.normal((28, 28, 1)) # Expand D to (1,28,28,1), then concatenate with C C_updated = tf.concat([C, tf.expand_dims(D, axis=0)], axis=0) print(C_updated.shape) # Output: (3, 28, 28, 1)
Option 2: Use tf.Variable for repeated appends (similar to +=)
If you need to append multiple tensors over time, use a tf.Variable (a mutable tensor wrapper). You can update it in-place using assign():
# Convert C to a Variable C_var = tf.Variable(C) # Append tensor D D = tf.random.normal((28, 28, 1)) C_var.assign(tf.concat([C_var, tf.expand_dims(D, axis=0)], axis=0)) print(C_var.shape) # Output: (3, 28, 28, 1) # Append another tensor E later E = tf.random.normal((28, 28, 1)) C_var.assign(tf.concat([C_var, tf.expand_dims(E, axis=0)], axis=0)) print(C_var.shape) # Output: (4, 28, 28, 1)
This feels closest to the += behavior you're looking for, as you're updating the same variable each time.
First, reshape your (100,784) tensor to (100,28,28,1) using tf.reshape()—since 28*28=784, this works perfectly:
# Example (100,784) tensor img_array = tf.random.normal((100, 784)) # Reshape to (100,28,28,1) img_reshaped = tf.reshape(img_array, (100, 28, 28, 1)) print(img_reshaped.shape) # Output: (100, 28, 28, 1)
From here, you can use the same stacking/concatenation methods above:
- To combine this reshaped tensor with your existing stack
C, usetf.concat([C, img_reshaped], axis=0)to get a(102,28,28,1)tensor. - If you were building this tensor from individual
(28,28,1)images, you could usetf.stack()on a list of those images to create the(100,28,28,1)tensor directly.
内容的提问来源于stack exchange,提问作者NorwegianClassic

