Skip to content

Instantly share code, notes, and snippets.

@skeltonmod
Last active March 3, 2023 11:32
Show Gist options
  • Save skeltonmod/11fea448bae502920c492f11d81d7f23 to your computer and use it in GitHub Desktop.
Save skeltonmod/11fea448bae502920c492f11d81d7f23 to your computer and use it in GitHub Desktop.
CS302 - CNN

This is how you should structure your data models.

dataset/
    train/
        unripe/
            unripe_image1.jpg
            unripe_image2.jpg
            ...
        semi-ripe/
            semi_ripe_image1.jpg
            semi_ripe_image2.jpg
            ...
        ripe/
            ripe_image1.jpg
            ripe_image2.jpg
            ...
        overripe/
            overripe_image1.jpg
            overripe_image2.jpg
            ...
    test/
        unripe/
            unripe_image1.jpg
            unripe_image2.jpg
            ...
        semi-ripe/
            semi_ripe_image1.jpg
            semi_ripe_image2.jpg
            ...
        ripe/
            ripe_image1.jpg
            ripe_image2.jpg
            ...
        overripe/
            overripe_image1.jpg
            overripe_image2.jpg
            ...

This works best with NVIDIA GPUs that supports CUDA.

Installation

  • Install the required packages
    pip install -r requirements.txt
  • Install CUDA and cuDNN if you have an NVIDIA GPU

Usage

  • Inorder to get accurate results, run trainer.py and strucutre your dataset as shown above
  • To run the model on your own dataset, change the path in trainer.py to your dataset path
  • To use the trained model replace the model variable as below
      from keras.models import load_model
    
      # Load the saved model from the .h5 file
      model = load_model('path/to/model.h5')
    
      # Use the loaded model to make predictions
      predictions = model.predict(data)
# ELIJAH M. ABGAO
# BACHELOR SCIENCE IN COMPUTER SCIENCE
# CODE IS OLD AS FUCK NOT RECOMMENDED, SEE BELOW!
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
x_train = np.load('cherry_images.npy') # array of cherry images
y_train = np.load('cherry_labels.npy') # array of labels (ripe=1, unripe=0)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(image_width, image_height, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=10, validation_split=0.2)
x_test = np.load('cherry_images_test.npy') # array of cherry images for testing
y_test = np.load('cherry_labels_test.npy') # array of labels for testing
loss, accuracy = model.evaluate(x_test, y_test)
print('Test loss:', loss)
print('Test accuracy:', accuracy)
# 2023 Keynote: dapat naa koy bahin ani arjohn yawa ka
import numpy as np
import tensorflow as tf
import keras.utils as image
from keras.applications.vgg19 import preprocess_input
model = tf.keras.applications.VGG19(
weights="imagenet", include_top=False, input_shape=(224, 224, 3)
)
for layer in model.layers[:-5]:
layer.trainable = False
x = model.output
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dense(1024, activation="relu")(x)
x = tf.keras.layers.Dropout(0.5)(x)
x = tf.keras.layers.Dense(512, activation="relu")(x)
x = tf.keras.layers.Dropout(0.5)(x)
predictions = tf.keras.layers.Dense(4, activation="softmax")(x)
model = tf.keras.models.Model(inputs=model.input, outputs=predictions)
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# Assume that the training data is stored in the train_data directory
img = image.load_img("coffee_berry.png", target_size=(224, 224))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
ripeness_labels = {0: "Unripe", 1: "Semi-ripe", 2: "Ripe", 3: "Overripe"}
prediction = model.predict(img_array)
predicted_ripeness = ripeness_labels[np.argmax(prediction)]
# Print the predicted ripeness of the coffee berry
print("Predicted ripeness:", predicted_ripeness)
# TODO MAKE TKINTER GUI
numpy
tensorflow
keras
opencv-python
pillow
import numpy as np
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg19 import VGG19, preprocess_input
# Set up data generators for training and validation
train_datagen = ImageDataGenerator(
preprocessing_function=preprocess_input,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
)
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory(
"train", target_size=(224, 224), batch_size=32, class_mode="categorical"
)
test_generator = test_datagen.flow_from_directory(
"test", target_size=(224, 224), batch_size=32, class_mode="categorical"
)
# Load VGG19 model pre-trained on ImageNet dataset
base_model = VGG19(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
# Freeze all layers in the base model
for layer in base_model.layers:
layer.trainable = False
# Add a new classification layer on top of the VGG19 model
x = base_model.output
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dense(1024, activation="relu")(x)
x = tf.keras.layers.Dropout(0.5)(x)
x = tf.keras.layers.Dense(512, activation="relu")(x)
x = tf.keras.layers.Dropout(0.5)(x)
predictions = tf.keras.layers.Dense(4, activation="softmax")(x)
model = tf.keras.models.Model(inputs=base_model.input, outputs=predictions)
# Compile the model with categorical cross-entropy loss and Adam optimizer
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# Train the model on the training data and validate on the test data
model.fit(train_generator, epochs=10, validation_data=test_generator)
# Save the trained model to a file
model.save("coffee_ripeness_model.h5")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment