# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="4L_iAbXksgQl"
# """
#
# author: <NAME>,
#
# index: s12623,
#
# email: <EMAIL>
#
# To run module:
#
# import module into Google Colaboratory notebook and run.
#
# This module recognize type of animal according to given image of animal.
#
# Keras model is build as classification type and contains two types of classification neural network architecture.
#
# """

# + [markdown] id="pDagT1Ehspzd"
# **First model**

# + colab={"base_uri": "https://localhost:8080/"} id="Zn5tfQjbwUY-" executionInfo={"status": "ok", "timestamp": 1611883193216, "user_tz": -60, "elapsed": 2086, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="b7983c33-dcbc-4077-fe01-1a4d24dddf57"
# %tensorflow_version 2.x
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout, Conv2D, MaxPooling2D
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import random
print('Tensorflow version: ', tf.__version__)

# + colab={"base_uri": "https://localhost:8080/"} id="Y8vl9oqd1RfG" executionInfo={"status": "ok", "timestamp": 1611883198711, "user_tz": -60, "elapsed": 7559, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="d24df4b6-7b5b-4a88-8dd0-3ab20d1c8422"
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data()

# + colab={"base_uri": "https://localhost:8080/"} id="_Kt23fiZDPZt" executionInfo={"status": "ok", "timestamp": 1611883683045, "user_tz": -60, "elapsed": 491883, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="03aff38b-9b7b-4b70-d5cf-0f5dfde2984f"
print('before')
print('X_train size: ', len(X_train))
print('y_train size: ', len(y_train))
print()
print('still work:')
i = 0 
while not i == len(y_train):

  if y_train[i][0] in {0, 1, 8, 9}:
    X_train = np.delete(X_train, i, 0)
    y_train = np.delete(y_train, i, 0)
    i = i - 1
  i = i + 1

  if (i % (len(y_train) // 100)) == 0:
    print('{:.0%}'.format(i / len(y_train)), end=' ')
  if (i % (len(y_train) // 10)) == 0:
    print()

print()
print('done.')
print()
print('actual:')
print('X_train size: ', len(X_train))
print('y_train size: ', len(y_train))

# + colab={"base_uri": "https://localhost:8080/"} id="cMh3kjD09P_c" executionInfo={"status": "ok", "timestamp": 1611883697801, "user_tz": -60, "elapsed": 506626, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="63f130c0-a14d-40f0-a1ce-4eb548818fc2"
print('before')
print('X_test size: ', len(X_test))
print('y_test size: ', len(y_test))
print()
print('still work:')
i = 0 
while not i == len(y_test):

  if y_test[i][0] in {0, 1, 8, 9}:
    X_test = np.delete(X_test, i, 0)
    y_test = np.delete(y_test, i, 0)
    i = i - 1
  i = i + 1

  if (i % (len(y_test) // 100)) == 0:
    print('{:.0%}'.format(i / len(y_test)), end=' ')
  if (i % (len(y_test) // 10)) == 0:
    print()

print()
print('done.')
print()
print('actual:')
print('X_test size: ', len(X_test))
print('y_test size: ', len(y_test))

# + colab={"base_uri": "https://localhost:8080/"} id="lUeFrLkygV7L" executionInfo={"status": "ok", "timestamp": 1611883698307, "user_tz": -60, "elapsed": 507116, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="cf2df54c-c8ee-4d31-8fc8-731eef5608a7"
idx = 0
for y in y_train:
  if y[0] == 2:
    y_train[idx][0] = 0
  if y[0] == 3:
    y_train[idx][0] = 1
  if y[0] == 4:
    y_train[idx][0] = 2
  if y[0] == 5:
    y_train[idx][0] = 3
  if y[0] == 6:
    y_train[idx][0] = 4
  if y[0] == 7:
    y_train[idx][0] = 5
  idx = idx + 1

idx = 0
for y in y_test:
  if y[0] == 2:
    y_test[idx][0] = 0
  if y[0] == 3:
    y_test[idx][0] = 1
  if y[0] == 4:
    y_test[idx][0] = 2
  if y[0] == 5:
    y_test[idx][0] = 3
  if y[0] == 6:
    y_test[idx][0] = 4
  if y[0] == 7:
    y_test[idx][0] = 5
  idx = idx + 1

y_train_cat = to_categorical(y_train)
y_test_cat = to_categorical(y_test) 

print(y_train_cat.shape, y_test_cat.shape)


# + colab={"base_uri": "https://localhost:8080/"} id="dRt-L-JHutq2" executionInfo={"status": "ok", "timestamp": 1611883704012, "user_tz": -60, "elapsed": 512806, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="1780efb5-8968-4b5b-e25f-a570b7cb4e7d"
model = Sequential()
model.add(Conv2D(filters=32, 
                 kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, 
                 kernel_size=(3, 3),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=128, 
                 kernel_size=(3, 3),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(6, activation='softmax'))

model.summary()

model.compile(
            optimizer='adam', 
            loss='categorical_crossentropy',
            metrics=['categorical_accuracy'])

# + colab={"base_uri": "https://localhost:8080/"} id="lbxywzjjt7xw" executionInfo={"status": "ok", "timestamp": 1611883778162, "user_tz": -60, "elapsed": 586943, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="94e86a58-8f80-45d7-bbed-adc9b001aeb3"
model.fit(X_train, y_train_cat, epochs=20, validation_data=(X_test, y_test_cat))

# + colab={"base_uri": "https://localhost:8080/", "height": 356} id="M8vYE3DdVoBW" executionInfo={"status": "ok", "timestamp": 1611883778751, "user_tz": -60, "elapsed": 587518, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="7f27e2c6-9c7a-46b0-ec64-6408ea5e4870"
f, axarr = plt.subplots()
f.set_size_inches(16, 5)

animals_cifar10_map = {
    0: 'bird',
    1: 'cat',
    2: 'deer',
    3: 'dog',
    4: 'frog',
    5: 'horse'
}

i = random.randrange(0, len(X_test))
print(animals_cifar10_map[y_test[i][0]])
img = X_test[i]
axarr.imshow(img)

img_rgb = X_test[i].reshape(1,32,32,3) 
propability = model.predict(img_rgb)
max_prop_idx = np.argmax(propability)
predicted_animal = animals_cifar10_map[max_prop_idx]
print('prediction of animal: ', predicted_animal)


# + [markdown] id="66Y5g6q2swuo"
# **Second model**

# + colab={"base_uri": "https://localhost:8080/"} id="1_OOUAOws0OD" executionInfo={"status": "ok", "timestamp": 1611883860121, "user_tz": -60, "elapsed": 604, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="0ae8966f-fc15-4a07-ddd3-4e8a0c795448"
model = Sequential()
model.add(Conv2D(filters=32, 
                 kernel_size=(2, 2),
                 activation='relu',
                 input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, 
                 kernel_size=(2, 2),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=128, 
                 kernel_size=(2, 2),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(2048, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(6, activation='softmax'))

model.summary()

model.compile(
            optimizer='adam', 
            loss='categorical_crossentropy',
            metrics=['categorical_accuracy'])

# + colab={"base_uri": "https://localhost:8080/"} id="Hzai5Wypt7GK" executionInfo={"status": "ok", "timestamp": 1611883956424, "user_tz": -60, "elapsed": 80299, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="da3e3e72-2550-40dd-846c-48d761faf0bc"
model.fit(X_train, y_train_cat, epochs=20, validation_data=(X_test, y_test_cat))

# + colab={"base_uri": "https://localhost:8080/", "height": 356} id="CTelacrot71L" executionInfo={"status": "ok", "timestamp": 1611884010309, "user_tz": -60, "elapsed": 716, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg75vIikNETLJCNaBd2LU4PCIaqbUU-ZYwJTMLkB5k=s64", "userId": "00227173073049198188"}} outputId="6feb4e57-904c-44d3-9d2f-0a16e0bf6d1c"
f, axarr = plt.subplots()
f.set_size_inches(16, 5)

animals_cifar10_map = {
    0: 'bird',
    1: 'cat',
    2: 'deer',
    3: 'dog',
    4: 'frog',
    5: 'horse'
}

i = random.randrange(0, len(X_test))
print(animals_cifar10_map[y_test[i][0]])
img = X_test[i]
axarr.imshow(img)

img_rgb = X_test[i].reshape(1,32,32,3) 
propability = model.predict(img_rgb)
max_prop_idx = np.argmax(propability)
predicted_animal = animals_cifar10_map[max_prop_idx]
print('prediction of animal: ', predicted_animal)


StarcoderdataJupyterScriptsDedupFiltered