python - Python 的 Numpy 数组维度的问题
问题描述
我正在努力解决一个我无法上班的问题!我目前正在使用 Tensorflow 并完成了基本教程。
正如您在本教程中所见,神经网络模型需要一个 train_images Numpy 形状数组,(60000, 28, 28)
因为本教程的训练集中有 60,000 张大小为 28x28 的图像。我正在阅读 Flavia 数据集,这是一组树叶图片。训练集由 1588 张图片组成,分辨率为 300x300px。这是我的代码:
for root, dirs, files in os.walk(pathname_data):
for name in files:
img = keras.preprocessing.image.load_img(os.path.join(root,name), color_mode="grayscale",target_size=(300,300)) #get image in 300x300 grayscale
array = keras.preprocessing.image.img_to_array(img) #convert to numpy array
array = array.squeeze(axis=2) #convert to 300x300 2d array
array = array / 255.0 #preprocess data
pathSegments = os.path.normpath(os.path.join(root,name)).split(os.sep) #split path
if pathSegments[len(pathSegments)-3] == "Train": #assign to training- or testSet
#TODO: how to store the 2x2 arrays ??
#store in training set
elif pathSegments[len(pathSegments)-3] == "Test":
#store in test set
我现在的问题是,如何存储“数组”以便最终得到一个(1588, 300, 300)
可以提供给模型的 - 形 Numpy 数组?我已经尝试过reshape
,追加和转置,但还没有成功:(非常感谢任何帮助!
解决方案
我假设您从文件生成的每个“数组”都是一个(300, 300)
形状
您可以预先生成数组并使用计数器
all_img = np.empty((1588, 300, 300))
count = 0
for root, dirs, files in os.walk(pathname_data):
for name in files:
...
all_img[count] = array.copy()
count += 1
...
或者您可以将所有图像附加到列表中并稍后将其更改为数组
all_img = []
for root, dirs, files in os.walk(pathname_data):
for name in files:
...
all_img.append(array)
...
all_img = np.array(all_img)
这两种方法都会给你一个(1588, 300, 300)
数组,我没有使用 Tensorflow 的经验,但这是你需要的形状。
推荐阅读
- mysql - MySQL 递归 CTE 表不存在
- c# - 在 C# 中使用 RemoteCertificateValidationCallback 进行 x509Certificate 吊销检查
- python - 离散数据的质量
- python - 从图中获取热图注释字典
- android - 如何支持 Firebase 库到 sdk 14
- json - 如何通过主键将嵌套的 JSON 索引连接到 SQL 中的多行
- php - Woocommerce 下拉屏幕,添加到购物车挂钩
- kubernetes - Kubernetes 提供垃圾外部 ip
- logstash - 从谷歌云存储有选择地下载堆栈驱动程序日志
- python - 为什么 Anaconda 发行版不能在 Windows 10 64 位上运行?