<jupyter_start><jupyter_text><jupyter_code>from glob import glob
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.layers import Dense, Dropout, Flatten, ReLU, LeakyReLU
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import SGD, Adam
cd drive/MyDrive/Colab_Notebooks/Persos/Computer_Vision/AVP/
ls
plt.figure(figsize=(8, 8))
plt.imshow(image.load_img("./train/predator/222.jpg"))
plt.axis("off")
plt.show();
train_path = "./train"
test_path = "./validation"
IMAGE_SIZE = [224, 224]
!ls
image_files = glob(train_path + "/*/*.jpg")
valid_image_files = glob(test_path + "/*/*.jpg")

folders = glob(train_path + "/*")
folders
plt.figure(figsize=(10,10))

plt.imshow(image.load_img(np.random.choice(image_files)))
plt.axis("off")
plt.show();
ptm = VGG16(include_top=False,
            input_shape=IMAGE_SIZE+[3])
ptm.trainable = False
K = 1 # or len(folders) if we don't use the sigmoid
x = Flatten()(ptm.output)
x = Dense(512, activation=LeakyReLU())(x)
x = Dropout(0.2)(x)
x = Dense(256, activation=LeakyReLU())(x)
x = Dropout(0.2)(x)
x = Dense(128, activation=LeakyReLU())(x)
x = Dropout(0.2)(x)
x = Dense(64, activation=LeakyReLU())(x)
x = Dropout(0.2)(x)
X = Dense(1, activation="sigmoid")(x)
model = Model(inputs=ptm.input, outputs=X)
model.summary()
gen = ImageDataGenerator(rotation_range=20,
                         width_shift_range=0.1,
                         height_shift_range=0.1,
                         shear_range=0.1,
                         zoom_range=0.2,
                         horizontal_flip=True,
                         preprocessing_function=preprocess_input)
batch_size = 32


train_generator = gen.flow_from_directory(train_path,
                                          shuffle=True,
                                          target_size=IMAGE_SIZE,
                                          batch_size=batch_size,
                                          class_mode="binary")


valid_generator = gen.flow_from_directory(test_path,
                                          target_size=IMAGE_SIZE,
                                          batch_size=batch_size,
                                          class_mode="binary")
model.compile(optimizer=SGD(learning_rate=0.001),
              loss="binary_crossentropy",
              metrics=["accuracy"])
history = model.fit_generator(train_generator,
                              validation_data=valid_generator,
                              epochs=20,
                              steps_per_epoch=int(np.ceil(len(image_files))/batch_size),
                              validation_steps=int(np.ceil(len(valid_image_files)/batch_size)))
plt.figure(figsize=(15, 6))

plt.subplot(1,2,1)
plt.plot(history.history["loss"], label="train loss")
plt.plot(history.history["val_loss"], label="validation loss")
plt.legend()

plt.subplot(1,2,2)
plt.plot(history.history["accuracy"], label="train acc")
plt.plot(history.history["val_accuracy"], label="validation acc")
plt.legend()
plt.show();
valid_image_files = glob(test_path + "/*/*.jpg")
txt = np.random.choice(valid_image_files)
test_image = image.load_img(txt, target_size=(224,224))
test_image = image.img_to_array(test_image)
test_image = preprocess_input(test_image)

test_image = np.expand_dims(test_image, axis=0)

proba = np.round(100*model.predict(test_image)[0][0],2)
if proba < 50:
  decision = "Alien"
  proba = np.round(100-proba,2)
else:
  decision = "Predator"
  proba = np.round(proba, 2)

plt.figure(figsize=(8, 8))

img = mpimg.imread(txt)
plt.axis("off")
plt.title(f"{decision} with a probability of {proba}%")
plt.imshow(img);<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13012295081967212, 'fraction_numerical': 0.0235655737704918, 'mean_word_length': 2.964467005076142, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '335276', 'license': 'MIT', 'n_tokens_mistral': 1347, 'n_tokens_neox': 1264, 'n_words': 214, 'path': 'AVP_Transfert_Learning.ipynb', 'repo_name': 'terencebeauj/Computer_Vision_Alien_VS_Predator', 'size': '3904'}