Reputation: 33
I write a classifier using data keras cifar10, I want to recognize only two classes, not all 10. I have a problem because when I learn for all 10 classes, the program works well and learns correctly, but when I take data only for two classes then I have a ValueError error: Data cardinality is ambiguous, Make sure all arrays contain the same number of samples. I don't understand why the error is because the data looks correct
from keras.datasets import cifar10
from matplotlib import pyplot as plt
from keras.utils import to_categorical
import numpy as np
from sklearn.model_selection import train_test_split
data = cifar10.load_data()
X=data[0][0].astype('float32') / 255.0
y=to_categorical(data[0][1])
X_new = []
y_new = []
# Split data to 2 classes
for x_change,y_change in zip (X, y):
if y_change[0] == 1 or y_change[1] == 1:
X_new.append(x_change)
y_new.append(y_change)
X_train, X_test, y_train, y_test = train_test_split(X_new, y_new, test_size=0.3)
for i in range(10):
print(y_train[i])
plt.imshow(X_train[i])
plt.show()
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
model3 = Sequential()
model3.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model3.add(MaxPooling2D((2, 2)))
model3.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model3.add(MaxPooling2D((2, 2)))
model3.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model3.add(MaxPooling2D((2, 2)))
model3.add(Flatten())
model3.add(Dense(10, activation='softmax'))
model3.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
history = model3.fit(X_train, y_train, epochs=600, batch_size=64, validation_data=(X_test, y_test))
Upvotes: 0
Views: 155
Reputation: 133
If you want to classify on 2 classes, the last layer must have one unit and the sigmoid activation. The last layer that you are using has 10 units and the activaction function is softmax, used for multiclass tasks.
---***---
You should verify too the batch size (see question1 and question2). Seems to me that you pass batch_size = 32 in the model construction and batch_size = 64 when fitting the model.
Upvotes: 1