chatgpt-4o-latest-20250326· OpenAI
LMArena Human Preference 140K
write the code for a mlp image classifier model using keras to train on the cifar100…
- User
write the code for a mlp image classifier model using keras to train on the cifar100 dataset.
- Assistant
Sure! Here's a complete example of a Multi-Layer Perceptron (MLP) image classifier using Keras to train on the CIFAR-100 dataset. Since MLPs are not ideal for image data (CNNs are better suited), we will flatten the image inputs and use dense layers.
📌 Note: CIFAR-100 images are 32x32 RGB images, so each image has shape (32, 32, 3), which we will flatten to (3072,) for the MLP.
✅ Code:
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.utils import to_categorical from tensorflow.keras.datasets import cifar100 # Load CIFAR-100 dataset (x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine') # Normalize pixel values to [0, 1] x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # Flatten the images x_train = x_train.reshape((x_train.shape[0], -1)) # shape: (50000, 3072) x_test = x_test.reshape((x_test.shape[0], -1)) # shape: (10000, 3072) # One-hot encode the labels y_train = to_categorical(y_train, 100) y_test = to_categorical(y_test, 100) # Build the MLP model model = Sequential([ Dense(512, activation='relu', input_shape=(3072,)), Dropout(0.5), Dense(256, activation='relu'), Dropout(0.5), Dense(100, activation='softmax') # 100 classes ]) # Compile the model model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # Print model summary model.summary() # Train the model model.fit(x_train, y_train, epochs=20, batch_size=128, validation_split=0.1) # Evaluate the model test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2) print(f"Test accuracy: {test_acc:.4f}")📝 Notes:
- We use
Dropoutlayers to help prevent overfitting. - The model uses
categorical_crossentropysince the labels are one-hot encoded. - You can adjust the number of layers, units, dropout rate, and training parameters to improve performance.
Let me know if you want a CNN version or want to use label_mode='coarse' (20 superclasses) instead!
- We use
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.