Last active
April 13, 2023 20:00
-
-
Save gogococo/726d9a04571255c471149f9864e57e83 to your computer and use it in GitHub Desktop.
Code sample used as is for the beginning of Build On Weekly. Dataset: https://www.kaggle.com/datasets/dansbecker/hot-dog-not-hot-dog Tutorial:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow | |
from tensorflow.keras.models import Sequential | |
from tensorflow.keras.layers import Dense, Conv2D, Flatten | |
import numpy as np | |
import os | |
import cv2 | |
# Configuration | |
img_width, img_height = 100, 100 | |
input_shape = (img_width, img_height, 1) | |
batch_size = 10 | |
no_epochs = 25 | |
no_classes = 5 | |
validation_split = 0.2 | |
verbosity = 1 | |
# Load data | |
def load_data(data_type='train', class_name='hot_dog'): | |
instances = [] | |
classes = [] | |
for filepath in os.listdir(f'hotdog/{data_type}/{class_name}'): | |
read_image = cv2.imread(f'hotdog/{data_type}/{class_name}/{format(filepath)}', 0) | |
try: | |
resized_image = cv2.resize(read_image, (img_width, img_height)) | |
except: | |
# It's cool, ignore Mac thumbnails | |
print(filepath) | |
instances.append(resized_image) | |
classes.append(0 if class_name == 'not_hot_dog' else 1) | |
return (instances, classes) | |
# Model creation | |
def create_model(): | |
model = Sequential() | |
model.add(Conv2D(4, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) | |
model.add(Conv2D(8, kernel_size=(3, 3), activation='relu')) | |
model.add(Conv2D(12, kernel_size=(3, 3), activation='relu')) | |
model.add(Flatten()) | |
model.add(Dense(256, activation='relu')) | |
model.add(Dense(no_classes, activation='softmax')) | |
return model | |
# Model compilation | |
def compile_model(model): | |
model.compile(loss=tensorflow.keras.losses.sparse_categorical_crossentropy, | |
optimizer=tensorflow.keras.optimizers.Adam(), | |
metrics=['accuracy']) | |
return model | |
# Model training | |
def train_model(model, X_train, y_train): | |
model.fit(X_train, y_train, | |
batch_size=batch_size, | |
epochs=no_epochs, | |
verbose=verbosity, | |
shuffle=True, | |
validation_split=validation_split) | |
return model | |
# Model testing | |
def test_model(model, X_test, y_test): | |
score = model.evaluate(X_test, y_test, verbose=0) | |
print(f'Test loss: {score[0]} / Test accuracy: {score[1]}') | |
return model | |
# Predict | |
def predict_model(image_path): | |
# Load and preprocess image | |
img = cv2.imread(image_path, 0) | |
resized_img = cv2.resize(img, (img_width, img_height)) | |
input_img = np.array(resized_img).reshape(1, img_width, img_height, 1) | |
# Predict class probabilities | |
class_probabilities = model.predict(input_img) | |
# Check if image contains a hotdog | |
contains_hotdog = class_probabilities[0, 1] > 0.5 | |
print(f'The image {image_path} contains a hotdog: {contains_hotdog}') | |
# CLICKING EVERYTHING TOGETHER | |
# Load and merge training data | |
X_train_nh, y_train_nh = load_data(data_type='train', class_name='not_hot_dog') | |
X_train_h, y_train_h = load_data(data_type='train', class_name='hot_dog') | |
X_train = np.array(X_train_nh + X_train_h) | |
X_train = X_train.reshape((X_train.shape[0], img_width, img_height, 1)) | |
y_train = np.array(y_train_nh + y_train_h) | |
# Load and merge testing data | |
X_test_nh, y_test_nh = load_data(data_type='test', class_name='not_hot_dog') | |
X_test_h, y_test_h = load_data(data_type='test', class_name='hot_dog') | |
X_test = np.array(X_test_nh + X_test_h) | |
X_test = X_test.reshape((X_test.shape[0], img_width, img_height, 1)) | |
y_test = np.array(y_test_nh + y_test_h) | |
# Create and train the model | |
model = create_model() | |
model = compile_model(model) | |
model = train_model(model, X_train, y_train) | |
model = test_model(model, X_test, y_test) | |
predict_model('classic-hot-dog.png') | |
predict_model('person.png') | |
predict_model('burger.jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment