<jupyter_start><jupyter_text><jupyter_code>import tensorflow as tf<jupyter_output><empty_output><jupyter_text>Retrieve images for testing<jupyter_code>!wget -q -O lemon.jpg --no-check-certificate "https://docs.google.com/uc?export=download&id=1JSgQ9qgi9nO9t2aGEk-zA6lzYNUT9vZJ"
!wget -q -O viaduct.jpg --no-check-certificate "https://docs.google.com/uc?export=download&id=1sQzMKmyCR5Tur19lP3n1IIlEMG_o6Mct"
!wget -q -O water_tower.jpg --no-check-certificate "https://docs.google.com/uc?export=download&id=1cPAQD1O6mAiMbg0fmG5HIk8OuO_BSC6J"<jupyter_output><empty_output><jupyter_text>ImageNet labels<jupyter_code>!wget -O labels.txt --quiet https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt

# read the categories text file
with open('labels.txt', 'r') as txt_file:
    categories = txt_file.read().splitlines()
    
# number of labels
num_class = len(categories)
print(num_class)<jupyter_output><empty_output><jupyter_text>Google's Mobilenet v1 model<jupyter_code>import tensorflow_hub as hub
from tensorflow.keras import Sequential

module_url = 'https://tfhub.dev/google/imagenet/mobilenet_v1_050_160/classification/4'

model = Sequential([
    hub.KerasLayer(module_url)
])

model.build( input_shape = [None, 160, 160, 3])
# Import and preprocess 3 sample ImageNet images
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import numpy as np

lemon_img = load_img("lemon.jpg", target_size=(160, 160))
viaduct_img = load_img("viaduct.jpg", target_size=(160, 160))
water_tower_img = load_img("water_tower.jpg", target_size=(160, 160))

# convert image to array
img_arr = img_to_array(water_tower_img)

# normalize
img_arr = img_arr / 255.0

# expand_dimensions
img_arr = img_arr[np.newaxis, ...]

# predict
predictions = model.predict(img_arr)

# get top 5 positions
k = 5
sort = np.argsort(-predictions[0])
top_k = sort[:k]

# display top 5
for i in top_k:
    print('{} = {}'.format(categories[i], predictions[0][i]))<jupyter_output><empty_output><jupyter_text>Function to display top 5 predictions<jupyter_code>import pandas as pd

def get_top_5_predictions(img):
    x = img_to_array(img)[np.newaxis, ...] / 255.0
    preds = model.predict(x)
    top_preds = pd.DataFrame(columns=['prediction'],
                             index=np.arange(5)+1)
    sorted_index = np.argsort(-preds[0])
    for i in range(5):
        ith_pred = categories[sorted_index[i]]
        top_preds.loc[i+1, 'prediction'] = ith_pred
            
    return top_preds
# top 5 predictions for lemon image
display(lemon_img)
get_top_5_predictions(lemon_img)
# top 5 predictions for viaduct image
display(viaduct_img)
get_top_5_predictions(viaduct_img)
# top 5 predictions for water tower image
display(water_tower_img)
get_top_5_predictions(water_tower_img)<jupyter_output><empty_output><jupyter_text>Let's test with our own image<jupyter_code># load your own image

filepath = # path to your image file, example - 'image/lion.jpg'
my_image = load_img(filepath, target_size=(160, 160))
img_arr = img_to_array(my_image)

# normalize
img_arr = img_arr / 255.0

# expand_dimensions
img_arr = img_arr[np.newaxis, ...]

# predict
predictions = model.predict(img_arr)

# get top 5 positions
k = 5
sort = np.argsort(-predictions[0])
top_k = sort[:k]

# display top 5
for i in top_k:
    print(categories[i],' =' ,predictions[0][i])

display(my_image)<jupyter_output><empty_output><jupyter_text>Another way to load hub module<jupyter_code># load module
module = hub.load(module_url)

# predict
predictions = module(img_arr)[0]

# top 5 predictions
top_k_pred_values, top_k_indices = tf.math.top_k(predictions, k=5)
top_k_pred_values = top_k_pred_values.numpy()
top_k_indices = top_k_indices.numpy()

# Display top 5 predictions

for probability, index in zip(top_k_pred_values, top_k_indices):
    print( categories[index], probability)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11911499871366092, 'fraction_numerical': 0.025984049395420632, 'mean_word_length': 5.668953687821612, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '533714', 'license': 'MIT', 'n_tokens_mistral': 1530, 'n_tokens_neox': 1458, 'n_words': 277, 'path': 'coding-exercise/week5/part2/2_Tensorflow_hub.ipynb', 'repo_name': 'Aye-Nyein-Thaw/TensorFlow-Beginner', 'size': '3887'}