pip install tflearn
LALU TULISKAN PERINTAH INSTALLNYA
REFF: https://www.edureka.co/blog/convolutional-neural-network/
https://pythonprogramming.net/convolutional-neural-network-cnn-machine-learning-tutorial/
https://www.geeksforgeeks.org/image-classifier-using-cnn/
https://towardsdatascience.com/mnist-cnn-python-c61a5bce7a19
In [217]:
import cv2
import os
import numpy as np
from random import shuffle
from tqdm import tqdm
In [218]:
def uk(img):
#print(img)
uk1=len(img)
uk2=len(img[0])
uk3=''
try:
m=len(img[0][0])
uk3="x"+str(m)
except:
uk3=0
uk3=""
print(type(img))
print(str(uk1)+"x"+str(uk2)+uk3)
return "OK"
#Latihan
X=["AKU", "ANAK","KODE"]
type(X)
len(X)
print(X[0])
print(X[0][1])
uk(X)
Out[218]:
In [228]:
TRAIN_DIR = 'dataset_catdog/latih' #'daun_lib/train' #'E:/dataset / Cats_vs_Dogs / train'
TEST_DIR = 'dataset_catdog/uji' #'E:/dataset / Cats_vs_Dogs / test1'
IMG_SIZE = 400
LR = 1e-3
MODEL_NAME = 'apps-{}-{}.model'.format(LR, '6conv-basic')
In [229]:
'''Labelling the dataset'''
def label_img(img):
word_label = img.split('.')[-3]
# DIY One hot encoder
if word_label == 'cat': return [0, 0]
elif word_label == 'dog': return [1,1]
'''Creating the training data'''
def create_train_data():
training_data = []
for img in tqdm(os.listdir(TRAIN_DIR)):
label = label_img(img)
path = os.path.join(TRAIN_DIR, img)
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
training_data.append([np.array(img), np.array(label)])
shuffle(training_data)
np.save('train_data.npy', training_data)
return training_data
'''Processing the given test data'''
def process_test_data():
testing_data = []
for img in tqdm(os.listdir(TEST_DIR)):
path = os.path.join(TEST_DIR, img)
img_num = img.split('.')[0]
img_numy=0
if img_num=='cat':
img_numy=0
elif img_num=='dog':
img_numy=1
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
testing_data.append([np.array(img), img_num])
shuffle(testing_data)
np.save('test_data.npy', testing_data)
return testing_data
In [230]:
train_data = create_train_data()
test_data = process_test_data()
#train_data = np.load('train_data.npy')
#test_data = np.load('test_data.npy')
In [231]:
'''Creating the neural network using tensorflow'''
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
import tensorflow as tf
tf.reset_default_graph()
convnet = input_data(shape =[None, IMG_SIZE, IMG_SIZE, 1], name ='input')
convnet = conv_2d(convnet, 32, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 64, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 128, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 64, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 32, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = fully_connected(convnet, 1024, activation ='relu')
convnet = dropout(convnet, 0.8)
convnet = fully_connected(convnet, 2, activation ='softmax')
convnet = regression(convnet, optimizer ='adam', learning_rate = LR, loss ='categorical_crossentropy', name ='targets')
model = tflearn.DNN(convnet, tensorboard_dir ='log')
In [232]:
train =train_data# train_data[:-500]
test = test_data #train_data[-500:]
uk(train)
uk(test)
Out[232]:
In [233]:
'''Setting up the features and lables'''
# X-Features & Y-Labels
X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1) #7x400x400 array
Y = [i[1] for i in train] #7x2 list
test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1) #7x400x400 array
test_y=[i[1] for i in test] #7x3x1 list
In [235]:
'''Fitting the data into our model'''
# epoch = 5 taken
EPOCH=3
model.fit({'input': X}, {'targets': Y}, n_epoch = EPOCH,validation_set =({'input': test_x}, {'targets': Y}),snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)
try:
model.fit({'input': X}, {'targets': Y}, n_epoch = EPOCH,validation_set =({'input': test_x}, {'targets': Y}),snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)
except:
print("ERR")
model.save(MODEL_NAME)
In [227]:
'''Testing the data'''
import matplotlib.pyplot as plt
# if you need to create the data:
# test_data = process_test_data()
# if you already have some saved:
#test_data = np.load('test_data.npy')
fig = plt.figure()
#for num, data in enumerate(test_data[:20]):
for num, data in enumerate(test_data):
# cat: [1, 0]
# dog: [0, 1]
img_num = data[1]
img_data = data[0] #400x400 array
y = fig.add_subplot(4, 5, num + 1)
orig = img_data
data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1) #400x400x1 array
# model_out = model.predict([data])[0]
model_out = model.predict([data])[0]
print(model_out)
if np.argmax(model_out) == 1: str_label ='Dog'
else: str_label ='Cat'
print(str_label)
y.imshow(orig, cmap ='gray')
plt.title(str_label)
y.axes.get_xaxis().set_visible(False)
y.axes.get_yaxis().set_visible(False)
plt.show()
In [ ]:
len(train_data[0][0])
In [ ]:
uk(img_data)
uk(data)
In [ ]:
print(img_data)
In [ ]:
print(data)
In [ ]:
test_data[:20]
In [ ]:
Tidak ada komentar:
Posting Komentar