如何解决MNIST适配AlexNet时维度转换的ValueError问题?
修复MNIST灰度图转RGB三通道的维度不匹配问题
首先咱们来揪出你代码出错的根源:你的dim数组是(227,227)的形状,但numpy_imgs里的每个元素是(227,227,1)的单通道数组——两者维度不匹配,所以在执行np.stack时才会抛出“所有输入数组必须有相同形状”的错误。
快速修复你的原始代码
只需要给dim添加一个通道维度,让它和t[i]的形状保持一致就行:
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) batch=mnist.train.next_batch(10) X_batch = batch[0] batch_tensor = tf.reshape(X_batch, [10, 28, 28, 1]) resized_images = tf.image.resize_images(batch_tensor, [227,227]) with tf.Session() as sess: numpy_imgs = resized_images.eval(session=sess) # 形状为(10,227,227,1) r2=[] t=list(numpy_imgs) # 给dim添加通道维度,变成(227,227,1) dim = np.zeros((227,227,1)) for i in range(0,10): # 现在三个数组形状统一,可正常执行stack操作 R=np.stack((t[i], dim, dim), axis=2) r2.append(R) y3=np.asarray(r2) # 验证最终形状:输出应为(10,227,227,3) print(y3.shape)
更简洁高效的实现方式
其实完全不用手动循环和拼接,直接用numpy.repeat就能一键把单通道扩展成三通道,代码更简洁,运行效率也更高:
# 假设numpy_imgs的形状是(10,227,227,1) y3 = np.repeat(numpy_imgs, repeats=3, axis=3) # 验证形状 print(y3.shape) # 输出 (10,227,227,3)
这个方法直接在通道维度(axis=3)上把每个单通道的数值重复3次,完美得到AlexNet需要的RGB输入格式。
如果你的环境是TensorFlow 2.x,还可以用框架自带的工具直接转换,连numpy操作都省了:
# 在TensorFlow 2.x中,resize后直接转RGB resized_images = tf.image.resize(batch_tensor, [227,227]) rgb_images = tf.image.grayscale_to_rgb(resized_images) # 转换成numpy数组直接调用numpy()方法 y3 = rgb_images.numpy()
内容的提问来源于stack exchange,提问作者Bckandemir
相关产品推荐
相关产品推荐

