<jupyter_start><jupyter_text><jupyter_code>from tensorflow.keras.applications import ResNet50, VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Conv2D
from keras.models import Model


model = ResNet50(weights='imagenet')
print(model.summary())


# Map layer to index vice versa
layer_name_to_index = {}
index_to_layer_name = {}
layers = []
for i, layer in enumerate(model.layers):
  layer_name_to_index['' + layer.name] = i
  index_to_layer_name[i] = layer.name
  layers.append(layer)


print(layer_name_to_index['conv1_bn'])
print(index_to_layer_name[7])
tmp_layer = model.get_layer(index_to_layer_name[7])
print(tmp_layer.weights)

print("\n\nLength:")
print(len(tmp_layer.weights))
print(tmp_layer.trainable_weights)
print('\n\n')
print(tmp_layer.non_trainable_weights)
tmp_layer.trainable = False
print(tmp_layer.trainable_weights)
print('\n\n')
print(tmp_layer.non_trainable_weights)<jupyter_output>[]



[<tf.Variable 'conv2_block1_1_conv/kernel:0' shape=(1, 1, 64, 64) dtype=float32, numpy=
array([[[[ 0.08688796, -0.26190212,  0.06590839, ..., -0.02883554,
          -0.16405106, -0.00745971],
         [ 0.01356522,  0.02057924, -0.03024781, ..., -0.01544086,
           0.02114245, -0.02121195],
         [-0.02776849, -0.00934073,  0.00506952, ..., -0.00039864,
          -0.00157149,  0.00997116],
         ...,
         [-0.00766947,  0.00688486,  0.00997647, ..., -0.0170019 ,
           0.00468291,  0.03455077],
         [-0.02132323,  0.01440203, -0.00365784, ...,  0.01140573,
          -0.01464687,  0.0494004 ],
         [-0.01673706,  0.01452293, -0.26559788, ...,  0.02150083,
          -0.10702326, -0.08648951]]]], dtype=float32)>, <tf.Variable 'conv2_block1_1_conv/bias:0' shape=(64,) dtype=float32, numpy=
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0.,[...]<jupyter_text>Layer insertion in middle
https://stackoverflow.com/questions/45306433/removing-then-inserting-a-new-middle-layer-in-a-keras-model<jupyter_code>print(layer_name_to_index['conv2_block2_1_conv'])
vgg_model = VGG16(weights='imagenet')
print(vgg_model.summary())
# Disassemble layers
net_layers = [l for l in vgg_model.layers]

# Defining new convolutional layer.
# Important: the number of filters should be the same!
# Note: the receiptive field of two 3x3 convolutions is 5x5.
new_conv = Conv2D(filters=64, 
                  kernel_size=(5, 5),
                  name='new_conv',
                  padding='same')(net_layers[0].output)

# Now stack everything back
# Note: If you are going to fine tune the model, do not forget to
#       mark other layers as un-trainable

x = new_conv
for i in range(3, len(net_layers)):
    net_layers[i].trainable = False
    x = net_layers[i](x)

# Final touch
result_model = Model(inputs=net_layers[0].input, outputs=x)
result_model.summary()
!wget "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/RayBanAviator.jpg/1200px-RayBanAviator.jpg" -O "sunglass.jpg"
img_path = 'sunglass.jpg'

img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
 
#decode the results into a list of tuples (class, description, probability)
#(one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])
# Bad results since the layer weights are just random and not trained
preds = result_model.predict(x)
 
#decode the results into a list of tuples (class, description, probability)
#(one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])
preds = vgg_model.predict(x)
 
#decode the results into a list of tuples (class, description, probability)
#(one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14576352321685015, 'fraction_numerical': 0.10507419818094782, 'mean_word_length': 3.6381798002219754, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '348517', 'license': 'MIT', 'n_tokens_mistral': 1819, 'n_tokens_neox': 1562, 'n_words': 343, 'path': 'tensorflow/Tensorflow_Keras_Layer_Extraction_Name_Index_Mapping.ipynb', 'repo_name': 'quickgrid/code-lab', 'size': '4178'}