i encoutred this exception : RuntimeWarning: invalid value encountered in true_divide
x /= x.std ()
when i use the argument :
np.seterr(divide=‘ignore’, invalid=‘ignore’)
the plt dosent show anything, my code:
import tensorflow as tf
from keras_preprocessing.image import load_img, img_to_array
import numpy as np
import matplotlib.pyplot as plt
import os, random
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
model = tf.keras.models.load_model(mypath)
outputs = [layer.output for layer in model.layers[1:]]
vis_model = tf.keras.models.Model(inputs=model.input, outputs=outputs)
data_dir =r"G:\dogs_cats\training"
cats_dir = os.path.join(data_dir, "cat")
dogs_dir = os.path.join(data_dir, "dog")
train_cat_fnames = os.listdir( cats_dir )
train_dog_fnames = os.listdir( dogs_dir )
cat_img_files = [os.path.join(cats_dir, f) for f in train_cat_fnames]
dog_img_files = [os.path.join(dogs_dir, f) for f in train_dog_fnames]
img_path = random.choice(cat_img_files + dog_img_files)
img = load_img(img_path, target_size=(150, 150)) # this is a PIL image
x = img_to_array(img) # Numpy array with shape (150, 150, 3)
x = x.reshape((1,) + x.shape) # Numpy array with shape (1, 150, 150, 3)
# Scale by 1/255
x /= 255.0
os.system('cls')
map = vis_model.predict(x)
layer_names = [layer.name for layer in model.layers]
for layer_name, feature_map in zip(layer_names, map):
if len(feature_map.shape) == 4:
n_features = feature_map.shape[-1] # number of features in the feature map
size = feature_map.shape[ 1] # feature map shape (1, size, size, n_features)
# Tile the images in this matrix
display_grid = np.zeros((size, size * n_features))
#-------------------------------------------------
# Postprocess the feature to be visually palatable
#-------------------------------------------------
for i in range(n_features):
x = feature_map[0, :, :, i]
x -= x.mean()
x /= x.std ()
x *= 64
x += 128
x = np.clip(x, 0, 255).astype('uint8')
display_grid[:, i * size : (i + 1) * size] = x # Tile each filter into a horizontal grid
#-----------------
# Display the grid
#-----------------
scale = 20. / n_features
plt.figure( figsize=(scale * n_features, scale) )
plt.title ( layer_name )
plt.grid ( False )
plt.imshow( display_grid, aspect='auto', cmap='viridis' )
also doing this:
if x.any() != 0:
x /= x.std ()
will end the process with no errors but will show no greed