Python Keras ValueError:形状(无,1)和(无,48,48,96)不兼容
我有一个数据集,我正试图使用Keras来训练它,但每次我都会遇到这样的错误:“ValueError:Shapes(None,1)和(None,48,48,96)是不兼容的”,我无法找出它到底出了什么问题。我阅读了其他相关问题,但无法理解问题的核心Python Keras ValueError:形状(无,1)和(无,48,48,96)不兼容,python,tensorflow,machine-learning,keras,neural-network,Python,Tensorflow,Machine Learning,Keras,Neural Network,我有一个数据集,我正试图使用Keras来训练它,但每次我都会遇到这样的错误:“ValueError:Shapes(None,1)和(None,48,48,96)是不兼容的”,我无法找出它到底出了什么问题。我阅读了其他相关问题,但无法理解问题的核心 DATASET_PATH = "/Users/user/Documents/ML Projects/Dataset" CLASSNAME_SIZE = 96 IMG_SIZE = 48 #Creating Dictionary
DATASET_PATH = "/Users/user/Documents/ML Projects/Dataset"
CLASSNAME_SIZE = 96
IMG_SIZE = 48
#Creating Dictionary of Classname
with open(JSON_PATH) as classnameJSON:
CLASSNAME = json.loads(classnameJSON.read())
trainingData = []
X = []
Y = []
#loading data
def loadTrainingData():
for instance in range(CLASSNAME_SIZE):
joinedPath = os.path.join(DATASET_PATH, str(instance))
label = str(instance)
for img in os.listdir(joinedPath):
try:
img_array = cv2.imread(os.path.join(joinedPath,img), cv2.COLOR_BGR2RGB)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
trainingData.append([new_array, label])
except Exception as err:
pass
loadTrainingData()
print(len(trainingData))
def distributeTrainingData():
for img, label in trainingData:
X.append(img)
Y.append(label)
distributeTrainingData()
print("distributing data")
X = np.array(X, dtype='float32')
Y = np.array(Y, dtype='float32')
print(len(X))
print(len(Y))
def cnn_model():
model = Sequential()
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(CLASSNAME_SIZE, activation='softmax'))
return model
model = cnn_model()
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(X, Y, batch_size=32, epochs=3)
添加密集层之前,请尝试添加:
model.add(keras.layers.InputLayer(input_shape=(X.shape[1],))
在添加密集层之前,请尝试添加:
model.add(keras.layers.InputLayer(input_shape=(X.shape[1],))
您的代码有两个问题
首先,您需要决定是否要对目标进行热编码并使用categorical\u交叉熵
loss,或者将它们作为1D张量传递并使用sparse\u categorical\u交叉熵
loss
使用categorical\u crossentropy
loss时,将它们作为一维张量传递。这两者是不相容的。简单的解决方法是将损失更改为sparse\u categorical\u crossentropy
第二个问题是,您正在将3D张量(图像)传递到需要平面输入的密集层。如果不想使用卷积层(即使是),则需要在将输入传递到密集层之前将其展平。您可以使用keras.layers.flatte()
进行此操作
因此,将compile
方法更改为
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
并将展平
层添加到模型中
def cnn_model():
model = Sequential()
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(CLASSNAME_SIZE, activation='softmax'))
return model
model = cnn_model()
如果要在密集层之前添加一些卷积(keras.layers.Conv2D
)层,则将在卷积底部和密集顶部之间添加展平
层
def cnn_model():
model = Sequential()
model.add(Conv2D(...))
# ... more conv/pool layers
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(CLASSNAME_SIZE, activation='softmax'))
return model
您的代码有两个问题 首先,您需要决定是否要对目标进行热编码并使用
categorical\u交叉熵
loss,或者将它们作为1D张量传递并使用sparse\u categorical\u交叉熵
loss
使用categorical\u crossentropy
loss时,将它们作为一维张量传递。这两者是不相容的。简单的解决方法是将损失更改为sparse\u categorical\u crossentropy
第二个问题是,您正在将3D张量(图像)传递到需要平面输入的密集层。如果不想使用卷积层(即使是),则需要在将输入传递到密集层之前将其展平。您可以使用keras.layers.flatte()
进行此操作
因此,将compile
方法更改为
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
并将展平
层添加到模型中
def cnn_model():
model = Sequential()
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(CLASSNAME_SIZE, activation='softmax'))
return model
model = cnn_model()
如果要在密集层之前添加一些卷积(keras.layers.Conv2D
)层,则将在卷积底部和密集顶部之间添加展平
层
def cnn_model():
model = Sequential()
model.add(Conv2D(...))
# ... more conv/pool layers
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(CLASSNAME_SIZE, activation='softmax'))
return model
这也是一个很好的解决方案!这也是一个很好的解决方案!