Python 如何将MNIST列车图像从(60000,28,28)重塑为(60000,16,16)?

Python 如何将MNIST列车图像从(60000,28,28)重塑为(60000,16,16)?,python,keras,reshape,mnist,Python,Keras,Reshape,Mnist,我正在尝试使用Keras学习具有简单密集层的MNIST数据集。 我希望我的图像大小为16*16,而不是28*28。我用了很多方法,但都不管用。这是一个简单的密集网络: 导入keras 将numpy作为np导入 输入mnist 从tensorflow.keras.models导入顺序 从tensorflow.keras.layers导入稠密 从tensorflow.keras.utils导入到 train\u images=mnist.train\u images() 列车标签=列表列车标签()

我正在尝试使用Keras学习具有简单密集层的MNIST数据集。 我希望我的图像大小为16*16,而不是28*28。我用了很多方法,但都不管用。这是一个简单的密集网络:

导入keras
将numpy作为np导入
输入mnist
从tensorflow.keras.models导入顺序
从tensorflow.keras.layers导入稠密
从tensorflow.keras.utils导入到
train\u images=mnist.train\u images()
列车标签=列表列车标签()
test_images=mnist.test_images()
test_labels=mnist.test_labels()
#使图像正常化。
列车图像=(列车图像/255)-0.5
测试图像=(测试图像/255)-0.5
打印(序列图像.形状)
打印(测试图像.形状)
#将图像展平。
train_images=train_images.重塑(-1784))
test_images=test_images.重塑(-1784))
打印(序列图像.形状)
打印(测试图像.形状)
#建立模型。
模型=顺序([
密集型(10,激活=softmax',输入_形=(784,),
])
#编译模型。
model.compile(
优化器='adam',
损失class='classifical_crossentropy',
指标=[“准确度”],
)
#训练模型。
模型拟合(
列车图像,
分类(列车标签),
纪元=5,
批次大小=32,
)
#评估模型。
模型评估(
测试图像,
分类(测试标签)
)
#将模型保存到磁盘。
model.save_权重('model.h5'))

尝试此方法一次调整所有图像的大小-

#!pip install --upgrade tensorflow
#Assuming you are using tensorflow 2

import numpy as np
import tensorflow as tf

#creating dummy images
imgs = np.stack([np.eye(28), np.eye(28)])
print(imgs.shape)
#Output - (2,28,28) 2 images of 28*28


imgt = imgs.transpose(1,2,0)  #Bring the batch channel to the end (28,28,2)
imgs_resize = tf.image.resize(imgt, (16,16)).numpy() #apply resize (14,14,2)
imgs2 = imgs_resize.transpose(2,0,1) #bring the batch channel back to front (2,14,14)
print(imgs2.shape)
#Output - (2,16,16)

尝试此方法一次调整所有图像的大小-

#!pip install --upgrade tensorflow
#Assuming you are using tensorflow 2

import numpy as np
import tensorflow as tf

#creating dummy images
imgs = np.stack([np.eye(28), np.eye(28)])
print(imgs.shape)
#Output - (2,28,28) 2 images of 28*28


imgt = imgs.transpose(1,2,0)  #Bring the batch channel to the end (28,28,2)
imgs_resize = tf.image.resize(imgt, (16,16)).numpy() #apply resize (14,14,2)
imgs2 = imgs_resize.transpose(2,0,1) #bring the batch channel back to front (2,14,14)
print(imgs2.shape)
#Output - (2,16,16)