Skip to main content
 首页 » 编程设计

python之在 Python 中堆叠多维数组的数组

2025年05月04日25zengkefu

我真的无法理解这个……而且我不确定在这里使用堆叠是否合适。

A.shape = (28,28,1) 
B.shape = (28,28,1) 

如果我想将这些数组合并/添加/堆叠成这种格式:

C.shape = (2,28,28,1) 

我该怎么做?它是 += 版本吗?我可以将形状为 (28,28,1) 的新数组添加到现有堆栈中以获取 (3, 28,28,1)。

编辑

我有这个包含 100 张灰度图像的数组:(100, 784) 我想我可以使用 将其 reshape 为 (100,28,28,1) >tf. reshape 。

我想用 tf.image.per_image_standardization ( doc ) 标准化 100 张图像的所有像素值,但是这个函数只接受输入形状 (h,w,ch) 又名。 (28,28,1)。

关于如何优化它有什么建议吗?

代码

for i in range(epochs): 
    for j in range(samples/batch_size): 
 
        batch_xs, batch_ys = mnist.train.next_batch(batch_size) #(100,784) 
        batch_xsr = tf.reshape(batch_xs, [-1, 28, 28, 1]) # (100,28,28,1) 
 
        ...  
 
        #somehow use tf.image.per_image_standardization (input shape =  
        #(28,28,1)) on each of the 100 images, and end up with  
        #shape (100,28,28,1) again. 
 
        ... 
 
        _, loss = sess.run([train, loss_op], feed_dict={x: batch_xs, y: batch_ys}) 

self 注意:TensorFlow 需要在 feed dict 中使用 np.array。

请您参考如下方法:

你可以这样...

import numpy as np 
 
A = np.zeros(shape=(28, 28, 1)) 
B = np.zeros(shape=(28, 28, 1)) 
A.shape  # (28, 28, 1) 
B.shape  # (28, 28, 1) 
 
C = np.array([A, B]) 
 
C.shape  # (2, 28, 28, 1) 

然后使用它来添加更多,假设这里的'new'与A或B的形状相同。

def add_another(C, new): 
    return np.array(list(C) + [new])