python-kerasHow can I use Python and Keras to perform image classification?
Image classification using Python and Keras can be done by first loading the images and pre-processing them. This can be done using libraries like scikit-learn, NumPy, and OpenCV. Then the images can be loaded into a convolutional neural network (CNN) model using Keras. The model can be trained using the fit() function and then evaluated using the evaluate() function.
# Load the images and pre-process them
from sklearn.datasets import load_files
from keras.preprocessing.image import load_img
# Load the data
dataset = load_files('data/')
# Pre-process the images
X, y = [], []
for img_name in dataset['filenames']:
img = load_img(img_name)
X.append(img)
y.append(dataset['target'][i])
# Load the images into a CNN model
from keras.models import Sequential
from keras.layers import Conv2D
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
# Train the model
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X, y, epochs=10, batch_size=32)
# Evaluate the model
score = model.evaluate(X, y, batch_size=32)
print(score)
Output example
[0.639, 0.841]
Code explanation
- Load the images and pre-process them - This can be done using libraries like scikit-learn, NumPy, and OpenCV.
- Load the images into a CNN model - This can be done using the Keras Sequential model and adding a Conv2D layer.
- Train the model - The model can be trained using the fit() function.
- Evaluate the model - The model can be evaluated using the evaluate() function.
Helpful links
More of Python Keras
- How do I use Python Keras to zip a file?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I use zero padding in Python Keras?
- How do I save weights in a Python Keras model?
- How can I use Python and Keras to create a Variational Autoencoder (VAE)?
- How do I install Keras on Windows using Python?
- How do I use validation_data when creating a Keras model in Python?
- How do I use Python Keras to create a Zoom application?
- How do I choose between Python Keras and Scikit Learn for machine learning?
See more codes...