正如评论中所建议的那样,np.squeeze 是最有原则的方法。添加一些细节。
import numpy as np
image = np.ones(shape=(28, 28, 3, 1))
print(image.shape) # (28, 28, 3, 1)
image = np.squeeze(image, axis=-1)
print(image.shape) # (28, 28, 3)
我还强烈建议始终使用axis 参数明确指定要挤压的轴,以避免错误地删除其他单轴。实际上,np.squeeze 默认会删除所有单维条目。如果您加载例如,这可能会出现问题。一张灰度图。
gray = np.ones(shape=(28, 28, 1, 1))
print(gray.shape) # (28, 28, 1, 1)
gray = np.squeeze(gray)
print(gray.shape) # (28, 28) may not be what you want
编辑:让我再补充一句关于在这种情况下使用np.reshape 的注意事项。
np.reshape 确实有效。但是,值得注意的是,即使在不应该的情况下,它也能正常工作,这可能会导致令人讨厌的错误。示例:
# Due to a bug, you have an image whose shape is different from
# the one you expect, which is (28, 28, 3, 1)
image = np.ones(shape=(56, 14, 3, 1))
# Reshape will still work, since (56 * 13 * 3) == (28 * 28 * 3)
# so you won't notice - yet the reshaped image will be nonsense!
reshaped = np.reshape(image, (28, 28, 3))
print(reshaped.shape) # (28, 28, 3)
您也可以根据个人喜好简单地将索引用于相同目的。
image = np.ones(shape=(28, 28, 3, 1))
image = image[..., 0] # same as: image[:, :, :, 0]
print(image.shape) # (28, 28, 3)