Skip to content

Instantly share code, notes, and snippets.

@prateekchandrayan
Created November 23, 2017 07:02
Show Gist options
  • Save prateekchandrayan/1d0fda4e9be483e7344ff8d16044cf92 to your computer and use it in GitHub Desktop.
Save prateekchandrayan/1d0fda4e9be483e7344ff8d16044cf92 to your computer and use it in GitHub Desktop.
Kaggle Dog_vs_Cat in Keras test
import cv2 # working with, mainly resizing, images
import numpy as np # dealing with arrays
import os # dealing with directories
from random import shuffle # mixing up or currently ordered data that might lead our network astray in training.
from tqdm import tqdm # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion
import tensorflow as tf #Import Tensorflow
import glob #This will extract all files from the folder
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import h5py
from keras.models import model_from_json
from keras.models import load_model
#Make subfolder of labels in the train and validation folder
#Read data from this laptop
#Load images from folder train folder
counter = 0
for imgtrain in glob.glob("D:/Kaggle_data/dogs_vs_cats/train/*.jpg"):
cv_imgtrain = cv2.imread(imgtrain)
counter += 1
m_train = counter
print ("m_train =", m_train)
#Read data from this laptop
#Load images from folder test folder
counter = 0
for imgtest in glob.glob("D:/Kaggle_data/dogs_vs_cats/test1/*.jpg"):
cv_imgtest = cv2.imread(imgtest)
counter += 1
m_test = counter
print ("m_test =", m_test)
#Calculate shape of train
cv_imgtrain.shape
#Calculate shape of test
cv_imgtest.shape
# dimensions of our images.
img_width, img_height = 150, 150
train_data_dir = 'D:/Kaggle_data/dogs_vs_cats/train'
validation_data_dir = 'D:/Kaggle_data/dogs_vs_cats/validation'
nb_train_samples = 12300
nb_validation_samples = 200
epochs = 4
batch_size = 10
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model=Sequential()
model.add(Conv2D(32, (3,3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(32, (3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
train_datagen = ImageDataGenerator(rescale=1. / 255)
validation_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
model.save('first_try.h5')
#model.save_weights('first_try.h5')
from keras.models import load_model
import numpy as np
from keras.preprocessing import image
from keras import backend as K
from keras.preprocessing.image import img_to_array, load_img
test_model = load_model('first_try.h5')
img = load_img('D:/Kaggle_data/dogs_vs_cats/test1/2.jpg',False,target_size=(img_width,img_height))
x = img_to_array(img)
x = np.expand_dims(x, axis=0)
preds = test_model.predict_classes(x)
prob = test_model.predict_proba(x)
print(preds, prob)
#Testing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment