<jupyter_start><jupyter_text>Let's check some sample images<jupyter_code>photos = []
for X_batch, y_batch in sample_images:
    i=0
    while i < 2:
        photos.append(X_batch[i])
        pyplot.imshow(X_batch[i])
        pyplot.show()
        i=i+1
    break<jupyter_output><empty_output><jupyter_text>Build the model<jupyter_code>model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))

model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))

model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))

model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer=optimizers.RMSprop(lr=1e-4),
              metrics=['acc'])
model.summary()<jupyter_output>_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_4 (Conv2D)            (None, 148, 148, 32)      896       
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 74, 74, 32)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 72, 72, 64)        18496     
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 36, 36, 64)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 34, 34, 128)       73856     
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 17, 17, 128)       0         
_________________________________________________________________
conv2d_7 ([...]<jupyter_text>Now let's train the model<jupyter_code>import keras
tb = keras.callbacks.TensorBoard(log_dir='./logs', histogram_freq=0, 
                            batch_size=32, write_graph=True, 
                            write_grads=False, write_images=False, 
                            embeddings_freq=0, embeddings_layer_names=None, 
                            embeddings_metadata=None)

history = model.fit_generator(
    train_images,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_images,
    validation_steps=nb_validation_samples // batch_size,
    callbacks = [tb]
)
model.save('cats-n-dogs_basic_model.h5')<jupyter_output><empty_output><jupyter_text>Plot the training data prediction accuracy and validation data prediction accuracyDivergence in acc and val_acc would indicate overfitting<jupyter_code>model = load_model('cats-n-dogs_basic_model.h5')
pyplot.plot(history.history['acc'])
pyplot.plot(history.history['val_acc'])
pyplot.legend(['acc', 'val_acc'])
pyplot.show()<jupyter_output><empty_output><jupyter_text>Now let's predict using our trained model<jupyter_code>def predict(image):
    im_np = np.asarray(image)
    im_array=np.expand_dims(im_np, axis=0) # need to do this since model.predict_classes takes array of images as input
    result = model.predict_classes(im_array)
    if result[0] == 1:
        return 'Dog'
    else:
        return 'Cat'<jupyter_output><empty_output><jupyter_text>Predict using a file from file system<jupyter_code>from PIL import Image

image_path = test_path + '/' + '12363.jpg'
pil_im = Image.open(image_path)
im = pil_im.resize((150,150))
pyplot.imshow(im)

print(predict(im))<jupyter_output>1/1 [==============================] - 0s
Dog<jupyter_text>Predict using an image from a URL<jupyter_code>import urllib
import cv2

def url_to_image(url):
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    image = cv2.resize(image, (150,150))
    return image

cat_image = 'http://www.ottawafamilyliving.com/wp-content/uploads/2017/05/cat.jpg'
dog_image = 'http://cdn3-www.dogtime.com/assets/uploads/2011/01/file_23262_entlebucher-mountain-dog-300x189.jpg'

image = url_to_image(dog_image)

pyplot.imshow(image)

print(predict(image))<jupyter_output>1/1 [==============================] - 0s
Dog
{'fraction_non_alphanumeric': 0.14231793960923622, 'fraction_numerical': 0.04196269982238011, 'mean_word_length': 4.5140758873929006, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '248054', 'license': 'MIT', 'n_tokens_mistral': 1570, 'n_tokens_neox': 1443, 'n_words': 245, 'path': 'cats-and-dogs/cats-n-dogs-basic.ipynb', 'repo_name': 'prabhatsharma/deep-learning', 'size': '4504'}