!pip install opencv-python
Collecting opencv-python
Downloading opencv_python-4.5.3.56-cp37-cp37m-manylinux2014_x86_64.whl (49.9 MB)
|████████████████████████████████| 49.9 MB 22.8 MB/s
Requirement already satisfied: numpy>=1.14.5 in /shared-libs/python3.7/py/lib/python3.7/site-packages (from opencv-python) (1.19.5)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.5.3.56
WARNING: You are using pip version 21.2.2; however, version 21.2.3 is available.
You should consider upgrading via the '/root/venv/bin/python -m pip install --upgrade pip' command.
/work/cloned-repo
'CNN Model' 'KNN Model' README.md
!git clone -l -s git://github.com/rmcgrory2000/ML4Kids.git cloned-repo
Cloning into 'cloned-repo'...
warning: --local is ignored
remote: Enumerating objects: 4735, done.
remote: Counting objects: 100% (661/661), done.
remote: Compressing objects: 100% (656/656), done.
remote: Total 4735 (delta 3), reused 660 (delta 3), pack-reused 4074
Receiving objects: 100% (4735/4735), 226.51 MiB | 52.16 MiB/s, done.
Resolving deltas: 100% (10/10), done.
Checking out files: 100% (4720/4720), done.
#import libraries
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.optimizers import Adam
import random
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
print("Objective complete.")
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
%cd CNN\ Model\ Image\ Dataset
!ls
%cd Images\ to\ Test\ Model\ with
!ls
[Errno 2] No such file or directory: 'CNN Model Image Dataset'
/work/cloned-repo/CNN Model/CNN Model Image Dataset/Images to Test Model with
sheep wolf zombie
[Errno 2] No such file or directory: 'Images to Test Model with'
/work/cloned-repo/CNN Model/CNN Model Image Dataset/Images to Test Model with
sheep wolf zombie
#Paste your chosen location for the training images between "" in path_to_images
path_to_images = "/work/cloned-repo/CNN Model/CNN Model Image Dataset/Images to Train Model with"
size_of_image = 80
minecraft_mob_type = ["sheep", "wolf", "zombie"]
training_data = []
validation_data = []
count = 0
def create_data():
for category in minecraft_mob_type:
path = os.path.join(path_to_images, category,"")
class_num = minecraft_mob_type.index(category)
for mob_image in os.listdir(path):
try:
image_array = cv2.imread(os.path.join(path,mob_image))
new_array = cv2.resize(image_array, (size_of_image, size_of_image))
if (count==0):
training_data.append([new_array, class_num])
else:
validation_data.append([new_array, class_num])
except Exception as e:
continue
create_data()
count+=1
#Paste your chosen location for the validation images between "" in path_to_images
path_to_images = "/work/cloned-repo/CNN Model/CNN Model Image Dataset/Images to Validate Model with"
create_data()
FileNotFoundError: [Errno 2] No such file or directory: '/Users/Rebecca/Desktop/minecraft/CNN Model Images/validation images/sheep/'
print(len(training_data))
print(len(validation_data))
random.shuffle(training_data)
random.shuffle(validation_data)
for sample in training_data[:10]:
print(sample[1])
training_features = []
training_labels = []
validation_features = []
validation_labels = []
for features, label in training_data:
training_features.append(features)
training_labels.append(label)
training_features = np.array(training_features).reshape(-1, size_of_image, size_of_image, 3)
training_labels = np.array(training_labels)
for features, label in validation_data:
validation_features.append(features)
validation_labels.append(label)
validation_features = np.array(validation_features).reshape(-1, size_of_image, size_of_image, 3)
validation_labels = np.array(validation_labels)
training_features = training_features/255.0
validation_features = validation_features/255.0
model = Sequential()
model.add(Conv2D(32, (3,3), activation='relu', input_shape=(size_of_image, size_of_image, 3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(32, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.4))
model.add(Conv2D(64, (3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.4))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(3, activation='softmax'))
model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=Adam(learning_rate=0.0001), metrics=['accuracy'])
model.fit(training_features, training_labels, batch_size=4, epochs=50, validation_data=(validation_features, validation_labels))
path_to_test_images = "/Users/Rebecca/Desktop/minecraft/CNN Model Images/test images/"
sheep_num_right = 0
wolf_num_right = 0
zombie_num_right = 0
for category in minecraft_mob_type:
path = os.path.join(path_to_test_images, category,"")
for img in os.listdir(path):
try:
img_array = cv2.imread(os.path.join(path,img))
new_array = cv2.resize(img_array, (size_of_image, size_of_image))
output = new_array.reshape(-1, size_of_image, size_of_image, 3)
prediction = model.predict(output)
if ((category=="sheep") & (np.argmax(prediction)==0)):
sheep_num_right +=1
elif ((category=="wolf") & (np.argmax(prediction)==1)):
wolf_num_right += 1
elif ((category=="zombie") & (np.argmax(prediction)==2)):
zombie_num_right += 1
else:
continue
except Exception as e:
continue
sheep_percent = (sheep_num_right/21)
format_sheep = "{:.0%}".format(sheep_percent)
print("Sheep correct:", format_sheep)
wolf_percent = (wolf_num_right/20)
format_wolf = "{:.0%}".format(wolf_percent)
print("Wolf correct:", format_wolf)
zombie_percent = (zombie_num_right/19)
format_zombie = "{:.0%}".format(zombie_percent)
print("Zombie correct:", format_zombie)
model.save("Minecraft-CNN.model")