【发布时间】:2021-07-29 18:16:43
【问题描述】:
我对神经网络和机器学习非常陌生,但是,我已经为云和无云创建了训练数据,并使用了用于我的一个手势项目的相同模型。当我使用这个模型时,我最初遇到了类似的错误消息,它说:
ValueError: Shapes (64, 10) and (64, 4) are incompatible
我过去在一些手势代码中使用相同的模型。过去我收到过类似的错误消息,因为据我了解,训练数据只有 4 个选项,而我的模型试图拟合 10 个选项。并且不得不将最终的神经元数量从 10 个更改为 4 个。
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import random
from tqdm import tqdm
import tensorflow as tf
from keras import layers
from keras import models
#Loading the traning data
DATADIR = "D:/Python_Code/Machine_learning/Cloud_Trainin_Data"
CATEGORIES = ["Clouds", "Normal_Terrain"]
training_data = []
for category in CATEGORIES: # do dogs and cats
path = os.path.join(DATADIR,category) # create path to dogs and cats
class_num = CATEGORIES.index(category) # get the classification (0 or a 1). 0=dog 1=cat
for img in tqdm(os.listdir(path)): # iterate over each image per dogs and cats
img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE) # convert to array
height = 1000
dim = None
(h, w) = img_array.shape[:2]
r = height / float(h)
dim = (int(w * r), height)
resized = cv2.resize(img_array, dim, interpolation = cv2.INTER_AREA)
training_data.append([resized, class_num]) # add this to our training_data
print(len(training_data))
random.shuffle(training_data)
for sample in training_data[:10]:
print(sample[1])
X = []
y = []
for features,label in training_data:
X.append(features)
y.append(label)
hh,ww = resized.shape
X = np.array(X).reshape(-1, hh, ww, 1)
y = np.array(y)
#Normalizing the data
X = X/255.0
#Building the Model
model=models.Sequential()
model.add(layers.Conv2D(32, (5, 5), strides=(2, 2), activation='relu', input_shape=X.shape[1:]))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(2, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
EPOCHS = 1
history = model.fit(X, y, batch_size = 5, epochs=EPOCHS, validation_split=0.1)
accuray, loss = model.evaluate(X, y)
print(accuray, loss)
model.save('Clouds.model')
loss = history.history["loss"]
acc = history.history["accuracy"]
epoch = np.arange(EPOCHS)
plt.plot(epoch, loss)
# plt.plot(epoch, val_loss)
plt.plot(epoch, acc, color='red')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.legend(['train', 'val'])
plt.show()
但是在这种情况下,当我应用相同的解决方案时,错误消息不断出现。
有什么建议吗?
【问题讨论】:
-
将损失
categorical_crossentropy更改为binary_crossentropy,因为您的输出标签是二进制的。还将Softmax更改为Sigmoid,并将最后一个密集层中的值2更改为1。谢谢! -
好的,为什么我需要改变我的损失是有道理的,但是从 2 到 1 的密集层有什么作用?我的印象是最后一层的神经元数量应该与您拥有的选项数量相同。
标签: python tensorflow machine-learning image-classification