英文:
ValueError: Shapes (None, 1) and (None, 30, 30, 3, 1) are incompatible
问题
以下是您要翻译的代码部分:
我正在进行一个练习,使用卷积神经网络对图像进行分类。必须使用OpenCV读取图像。`load_data` 已经实现,但我似乎无法实现 `get_model`,因为出现了以下错误。
每当我尝试运行这段代码时,都会出现错误 `ValueError: 形状 (None, 1) 和 (None, 30, 30, 1) 不兼容`。我已经尝试过搜索,但无法理解为什么会发生这个错误。如果有人能帮助我理解这个错误是什么以及为什么会发生,我将非常感激。
```python
import cv2
import numpy as np
import os
import sys
import tensorflow as tf
from sklearn.model_selection import train_test_split
EPOCHS = 10
IMG_WIDTH = 30
IMG_HEIGHT = 30
NUM_CATEGORIES = 43
TEST_SIZE = 0.4
def main():
# 检查命令行参数
if len(sys.argv) not in [2, 3]:
sys.exit("用法: python traffic.py data_directory [model.h5]")
# 获取所有图像文件的图像数组和标签
images, labels = load_data(sys.argv[1])
# 将数据分为训练集和测试集
labels = tf.keras.utils.to_categorical(labels)
x_train, x_test, y_train, y_test = train_test_split(
np.array(images), np.array(labels), test_size=TEST_SIZE
)
# 获取已编译的神经网络模型
model = get_model()
# 在训练数据上拟合模型
model.fit(x_train, y_train, epochs=EPOCHS)
# 评估神经网络性能
model.evaluate(x_test, y_test, verbose=2)
# 将模型保存到文件
if len(sys.argv) == 3:
filename = sys.argv[2]
model.save(filename)
print(f"模型已保存到 {filename}。")
def load_data(data_dir):
"""
从目录 `data_dir` 中加载图像数据。
假设 `data_dir` 中有一个以每个类别命名的目录,编号从0到NUM_CATEGORIES-1。在每个类别目录内都将有一些图像文件。
返回元组 `(images, labels)`。`images` 应该是数据目录中所有图像的列表,其中每个图像都以形状为 IMG_WIDTH x IMG_HEIGHT x 3 的numpy数组格式。`labels` 应该是整数标签的列表,表示每个相应的 'images' 的类别。
"""
images = []
labels = []
for i in range(NUM_CATEGORIES):
path = f'{data_dir}{os.sep}{i}'
for file in os.listdir(path):
file_path = f'{path}{os.sep}{file}'
print(f"读取 {file_path}...")
image = cv2.imread(file_path)
image = cv2.resize(image, (IMG_WIDTH, IMG_HEIGHT))
images.append(image)
labels.append(i)
return (images, labels)
def get_model():
"""
返回一个已编译的卷积神经网络模型。假设第一层的 `input_shape` 为 `(IMG_WIDTH, IMG_HEIGHT, 3)`。输出层应该有 `NUM_CATEGORIES` 个单元,每个单元对应一个类别。
"""
# 卷积神经网络
model = tf.keras.Sequential([
# 输入
tf.keras.layers.Dense(1, activation="relu") ,
# 隐藏层
# 输出
tf.keras.layers.Dense(NUM_CATEGORIES)
])
model.compile(
optimizer="adam",
loss=tf.keras.losses.CategoricalCrossentropy()
)
return model
if __name__ == "__main__":
main()
英文:
I am doing an exercise to classify images using a convolutional neural network. The images must be read using OpenCV. load_data
is already implemented, but I can't seem to implement get_model
because of this error.
Whenever I attemp to run this code, I get an error ValueError: Shapes (None, 1) and (None, 30, 30, 1) are incompatible
. I have tried searching but I can't understand why this error is occurring. If anyone could help me understand what this error is and why it is happening , I would be very grateful.
import cv2
import numpy as np
import os
import sys
import tensorflow as tf
from sklearn.model_selection import train_test_split
EPOCHS = 10
IMG_WIDTH = 30
IMG_HEIGHT = 30
NUM_CATEGORIES = 43
TEST_SIZE = 0.4
def main():
# Check command-line arguments
if len(sys.argv) is not in [2, 3]:
sys.exit("Usage: python traffic.py data_directory [model.h5]")
# Get image arrays and labels for all image files
images, labels = load_data(sys.argv[1])
# Split data into training and testing sets
labels = tf.keras.utils.to_categorical(labels)
x_train, x_test, y_train, y_test = train_test_split(
np.array(images), np.array(labels), test_size=TEST_SIZE
)
# Get a compiled neural network
model = get_model()
# Fit model on training data
model.fit(x_train, y_train, epochs=EPOCHS)
# Evaluate neural network performance
model.evaluate(x_test, y_test, verbose=2)
# Save model to file
if len(sys.argv) == 3:
filename = sys.argv[2]
model.save(filename)
print(f"Model saved to {filename}.")
def load_data(data_dir):
"""
Load image data from directory `data_dir`.
Assume `data_dir` has one directory named after each category, numbered
0 through NUM_CATEGORIES = 1. Inside each category directory will be some
number of image files
Return the tuple `(images, labels)`. `images` should be a list of all
of the images in the data directory, where each image is formatted as a
numpy ndarray with dimensions IMG_WIDTH x IMG_HEIGHT x 3. `labels` should
be a list of integer labels, representing the categories for each of the
corresponding 'images'.
"""
images = []
labels = []
for i in range (NUM_CATEGORIES):
path = f'{data_dir} {os.sep}{i}'
for file in os.listdir(path):
file_path = f'{path}{os.sep}{file}'
print(f"Reading {file_path}...")
image = cv2.imread(file_path)
image = cv2.resize(image, (IMG_WIDTH, IMG_HEIGHT))
images.append(image)
labels.append(i)
return (images, labels)
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
# Convolutional Neural Network
model = tf.keras.Sequential([
# input
tf.keras.layers.Dense(1, activation="relu") ,
# hidden layers
# output
tf.keras.layers.Dense(NUM_CATEGORIES)
])
model.compile(
optimizer="adam",
loss=tf.keras.losses.CategoricalCrossentropy()
)
return model
if __name__ == "__main__":
main()
答案1
得分: 0
因为你需要一个 CNN,但你只有这个 tf.keras.layers.Dense(1, activation="relu")
。这不是 CNN。这是 CNN 的一个示例:https://towardsdatascience.com/coding-a-convolutional-neural-network-cnn-using-keras-sequential-api-ec5211126875
英文:
Because you need a CNN, but you just have this tf.keras.layers.Dense(1, activation="relu")
. This is not CNN. Here is an example of CNN https://towardsdatascience.com/coding-a-convolutional-neural-network-cnn-using-keras-sequential-api-ec5211126875
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论