Mutliclass Image Classification with TensorFlow: A Step-by-Step Guide with Code Template
Python
This code is a basic template for multiclass image classification using TensorFlow. It involves preprocessing the data, defining a neural network model, compiling the model, training the model on the data, and evaluating the model's accuracy on the test set. The code makes use of popular libraries like NumPy, TensorFlow, and Keras.
1| import tensorflow as tf 2| from tensorflow import keras 3| from tensorflow.keras import layers 4| 5| # Step 1: We normalize the pixel values of 6| # the images by dividing them by 255.0 to 7| # scale them to the range of 0 to 1. 8| X_train = X_train.astype("float32") / 255.0 9| X_test = X_test.astype("float32") / 255.0 10| X_val = X_val.astype("float32") / 255.0 11| 12| # Step 2: We define the neural network model 13| # using the Keras Sequential API. In this example, 14| # we use two convolutional layers with max pooling 15| # followed by a dense output layer with softmax activation. 16| model = keras.Sequential([ 17| layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), 18| layers.MaxPooling2D((2, 2)), 19| layers.Conv2D(64, (3, 3), activation='relu'), 20| layers.MaxPooling2D((2, 2)), 21| layers.Flatten(), 22| layers.Dense(10, activation='softmax') 23| ]) 24| 25| # Step 3: We compile the model by specifying the optimizer, 26| # loss function, and metrics for evaluation. Here we use 27| # the Adam optimizer, sparse categorical cross-entropy loss 28| # and accuracy as the evaluation metric. 29| model.compile(optimizer='adam', 30| loss='sparse_categorical_crossentropy', 31| metrics=['accuracy']) 32| 33| # Step 4: Fit the model. We specify the number of epochs 34| # to train for and the validation data to evaluate the model 35| # after each epoch. 36| model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val)) 37| 38| # Step 5: We evaluate the trained model on the test data and 39| # print the test accuracy. 40| test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2) 41| print('Test accuracy:', test_acc)
147
131
125
118