Minggu, 02 Februari 2020

CNN CAT DOG

Install Lib dahulu : Buka Anaconda Prompt, juga semua library lainnya jika diperlukan
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

CNNQ-APP1
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)
AKU
K
<class 'list'>
3x3x1
Out[218]:
'OK'
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') 
100%|██████████| 20/20 [00:00<00:00, 417.78it/s]
100%|██████████| 10/10 [00:00<00:00, 303.84it/s]
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)
<class 'list'>
20x2x400
<class 'list'>
10x2x400
Out[232]:
'OK'
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) 
---------------------------------
Run id: apps-0.001-6conv-basic.model
Log directory: log/
INFO:tensorflow:Summary name Accuracy/ (raw) is illegal; using Accuracy/__raw_ instead.
---------------------------------
Training samples: 20
Validation samples: 10
--
Training Step: 1  | time: 3.594s
| Adam | epoch: 001 | loss: 0.00000 - acc: 0.0000 | val_loss: 1.04862 - val_acc: 0.0000 -- iter: 20/20
--
Training Step: 2  | total loss: 0.64419 | time: 3.479s
| Adam | epoch: 002 | loss: 0.64419 - acc: 0.7650 | val_loss: 0.41680 - val_acc: 0.0000 -- iter: 20/20
--
Training Step: 3  | total loss: 1.55079 | time: 3.268s
| Adam | epoch: 003 | loss: 1.55079 - acc: 0.1391 | val_loss: 0.44485 - val_acc: 1.0000 -- iter: 20/20
--
---------------------------------
Run id: apps-0.001-6conv-basic.model
Log directory: log/
---------------------------------
Training samples: 20
Validation samples: 10
--
Training Step: 4  | total loss: 0.90973 | time: 4.233s
| Adam | epoch: 004 | loss: 0.90973 - acc: 0.2223 | val_loss: 0.43005 - val_acc: 0.0000 -- iter: 20/20
--
Training Step: 5  | total loss: 0.78750 | time: 3.707s
| Adam | epoch: 005 | loss: 0.78750 - acc: 0.7607 | val_loss: 0.41800 - val_acc: 1.0000 -- iter: 20/20
--
Training Step: 6  | total loss: 0.74267 | time: 3.399s
| Adam | epoch: 006 | loss: 0.74267 - acc: 0.2717 | val_loss: 0.41713 - val_acc: 1.0000 -- iter: 20/20
--
INFO:tensorflow:C:\Users\USER\apps-0.001-6conv-basic.model is not in all_model_checkpoint_paths. Manually adding it.
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() 
[0.5570502  0.44294977]
Cat
[0.56809074 0.43190926]
Cat
[0.54562443 0.4543756 ]
Cat
[0.5489455  0.45105454]
Cat
[0.55359805 0.44640198]
Cat
[0.5518269 0.4481731]
Cat
[0.5352615  0.46473846]
Cat
[0.54566246 0.45433757]
Cat
[0.5587691 0.4412309]
Cat
[0.53780174 0.4621983 ]
Cat
[0.54609686 0.45390317]
Cat
[0.54953986 0.45046017]
Cat
[0.54347664 0.4565233 ]
Cat
[0.54267174 0.4573283 ]
Cat
[0.5512743 0.4487257]
Cat
[0.5691295  0.43087044]
Cat
[0.5531336 0.4468664]
Cat
[0.5431913  0.45680866]
Cat
[0.53809863 0.4619014 ]
Cat
[0.5487714  0.45122865]
Cat
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