In [6]:
from sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob
def load_dataset(path):
data = load_files(path)
files = np.array(data['filenames'])
n_target = len(set(data['target']))
targets = np_utils.to_categorical(np.array(data['target']), n_target)
return files, targets
cat_files, cat_targets = load_dataset('catImages')
# load list of cat names
cat_names = [item[10:-1] for item in sorted(glob("catImages/*/"))]
# print statistics about the dataset
print('There are %d total cat categories.' % len(cat_names))
print('There are %s total cat images.\n' % len(cat_files))
In [7]:
cat_names
Out[7]:
In [4]:
from keras.preprocessing import image
from tqdm import tqdm
def path_to_tensor(img_path):
# loads RGB image as PIL.Image.Image type
img = image.load_img(img_path, target_size=(224, 224))
# convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
x = image.img_to_array(img)
# convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
return np.expand_dims(x, axis=0)
def paths_to_tensor(img_paths):
list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
return np.vstack(list_of_tensors)
In [8]:
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# pre-process the data for Keras
cat_tensors = paths_to_tensor(cat_files).astype('float32')/255
In [11]:
from keras.applications.xception import Xception, preprocess_input
x = preprocess_input(paths_to_tensor(cat_files))
y = cat_targets
model = Xception(weights='imagenet', include_top=False)
cat_x = model.predict(x)
cat_y = y[:cat_x.shape[0]]
In [13]:
np.save('saved/bottleneck_features.npy', cat_x)
# cat_x = np.load('saved/bottleneck_features.npy')
cat_x.shape
Out[13]:
In [19]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=cat_x.shape[1:]))
Xception_model.add(Dense(len(cat_names), activation='softmax'))
Xception_model.summary()
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [20]:
Xception_model.fit(cat_x, cat_y, epochs=25, batch_size=26, verbose=1)
Out[20]:
In [21]:
from extract_bottleneck_features import *
from operator import itemgetter
def Xception_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_Xception(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = Xception_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return cat_names[np.argmax(predicted_vector)]
def Xception_top3_breeds(img_path):
# extract bottleneck features
bottleneck_feature = extract_Xception(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = Xception_model.predict(bottleneck_feature)[0]
# return dog breed that is predicted by the model
ind = np.argpartition(predicted_vector, -3)[-3:]
return sorted([(cat_names[ind[i]], predicted_vector[ind[i]]) for i in range(3)], key=itemgetter(1), reverse=True)
In [28]:
import matplotlib.pyplot as plt
%matplotlib inline
def cat_app(img_path):
import matplotlib.image as mpimg
print("Welcome to cat matrix v1.0! (from an AI)")
img = mpimg.imread(img_path)
plt.imshow(img)
plt.show()
print("seems like:")
for name, prob in Xception_top3_breeds(img_path):
print("{} with prob {}".format(name, prob))
In [29]:
cat_app("appImages/caturday-shutterstock_149320799.jpg")
In [30]:
cat_app("appImages/DSC_6037.head.png")
In [31]:
cat_app("appImages/IMG_0031 copy.jpg")
In [32]:
cat_app("appImages/IMG_0054.small.jpg")
In [33]:
cat_app("appImages/zmy.jpg")
In [34]:
cat_app("appImages/992cad0bjw1dzdm7ovlskj.jpg")
In [35]:
cat_app("appImages/WechatIMG31.jpeg")
In [36]:
cat_app("appImages/WechatIMG32.jpeg")
In [76]:
cat_app("cat-friends/WechatIMG35.jpeg")
In [ ]: