This code imports necessary libraries, including Keras for building neural networks, and additional libraries like Pandas for data manipulation and NumPy for numerical computation, as well as the os module for operating system functions. The imported libraries are used for tasks such as image processing, data analysis, and neural network model creation.
from keras.utils import to_categorical
from keras_preprocessing.image import load_img
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
import os
import pandas as pd
import numpy as np
# Import libraries for image processing and neural network
from keras.preprocessing.image import load_img, img_to_array
from keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
import os
import pandas as pd
import numpy as np
# Constants
IMAGE_SIZE = (256, 256) # resize image size
BATCH_SIZE = 32 # batch size for training
EPOCHS = 10 # number of epochs for training
# Load Image
def load_image(file_path):
"""
Load image from file path and resize it to IMAGE_SIZE.
Args:
file_path (str): path to the image file.
Returns:
image (numpy array): resized image.
"""
image = load_img(file_path, target_size=IMAGE_SIZE)
return img_to_array(image)
# Load Dataset
def load_dataset(data_dir):
"""
Load dataset from directory and convert image paths to numpy arrays.
Args:
data_dir (str): path to the dataset directory.
Returns:
images (numpy array): numpy array of image data.
labels (numpy array): numpy array of labels.
"""
images = []
labels = []
for category in os.listdir(data_dir):
category_dir = os.path.join(data_dir, category)
for file in os.listdir(category_dir):
file_path = os.path.join(category_dir, file)
image = load_image(file_path)
images.append(image)
labels.append(int(category))
return np.array(images), np.array(labels)
# Preprocess Data
def preprocess_data(images, labels):
"""
Convert image data to categorical labels and one-hot encode labels.
Args:
images (numpy array): numpy array of image data.
labels (numpy array): numpy array of labels.
Returns:
images (numpy array): numpy array of image data.
labels (numpy array): numpy array of one-hot encoded labels.
"""
images = images / 255 # normalize pixel values
labels = to_categorical(labels) # one-hot encode labels
return images, labels
# Build Model
def build_model():
"""
Build neural network model using Sequential API.
Returns:
model (keras model): built neural network model.
"""
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(len(os.listdir(data_dir)), activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
# Train Model
def train_model(model, images, labels):
"""
Train neural network model on dataset.
Args:
model (keras model): built neural network model.
images (numpy array): numpy array of image data.
labels (numpy array): numpy array of one-hot encoded labels.
"""
model.fit(images, labels, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.2)
# Main Function
def main():
data_dir = 'path/to/dataset' # replace with actual dataset path
images, labels = load_dataset(data_dir)
images, labels = preprocess_data(images, labels)
model = build_model()
train_model(model, images, labels)
if __name__ == '__main__':
main()
from keras.utils import to_categorical
from keras_preprocessing.image import load_img
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
keras.utils
: Contains utility functions for use during training.keras_preprocessing.image
: Provides functions for working with images.keras.models
: Allows the creation of neural network models.keras.layers
: Offers pre-built layers to add to the model.import os
import pandas as pd
import numpy as np
os
: Provides a way of using operating system dependent functionality.pandas
: A library for data manipulation and analysis.numpy
: A library for efficient numerical computation.