模型可视化
import tensorflow as tf
from tensorflow import keras
from keras import models
from keras.preprocessing import image
import numpy as np
import os
img_path=r"C:\Users\bxzyz\Desktop\doc\ocr\data\orc-data\annotations\charactor-008"
img_name=r"charactor-008_00223.bmp"
imgpath=os.path.join(img_path,img_name)
model = keras.models.load_model('D:\mydoc\ML\ocr2_IC_model_all4.h5')
img=image.load_img(imgpath,target_size=(75,45))
img_tensor=image.img_to_array(img)
img_tensor=np.expand_dims(img_tensor,axis=0)
print(img_tensor.shape)
(1, 75, 45, 3)
import matplotlib.pyplot as plt
plt.imshow(np.array(img_tensor[0],np.uint8))
plt.show()
output_4_0.png
from keras import models
layer_outputs=[layer.output for layer in model.layers[:4]]#提取前4层网络
activation_model=models.Model(inputs=model.input,outputs=layer_outputs)
activations=activation_model.predict(img_tensor)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-e0393a80deb5> in <module>
2
3 layer_outputs=[layer.output for layer in model.layers[:4]]#提取前4层网络
----> 4 activation_model=models.Model(inputs=model.input,outputs=layer_outputs)
5 activations=activation_model.predict(img_tensor)
D:\anaconda\envs\py3\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name + '` call to the ' +
90 'Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
D:\anaconda\envs\py3\lib\site-packages\keras\engine\network.py in __init__(self, *args, **kwargs)
92 'inputs' in kwargs and 'outputs' in kwargs):
93 # Graph network
---> 94 self._init_graph_network(*args, **kwargs)
95 else:
96 # Subclassed network
D:\anaconda\envs\py3\lib\site-packages\keras\engine\network.py in _init_graph_network(self, inputs, outputs, name, **kwargs)
239 # Keep track of the network's nodes and layers.
240 nodes, nodes_by_depth, layers, layers_by_depth = _map_graph_network(
--> 241 self.inputs, self.outputs)
242 self._network_nodes = nodes
243 self._nodes_by_depth = nodes_by_depth
D:\anaconda\envs\py3\lib\site-packages\keras\engine\network.py in _map_graph_network(inputs, outputs)
1432 layer=layer,
1433 node_index=node_index,
-> 1434 tensor_index=tensor_index)
1435
1436 for node in reversed(nodes_in_decreasing_depth):
D:\anaconda\envs\py3\lib\site-packages\keras\engine\network.py in build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
1413
1414 # Propagate to all previous tensors connected to this node.
-> 1415 for i in range(len(node.inbound_layers)):
1416 x = node.input_tensors[i]
1417 layer = node.inbound_layers[i]
TypeError: object of type 'InputLayer' has no len()
model.input
<tf.Tensor 'input_9_1:0' shape=(None, 75, 35, 3) dtype=float32>
first_layer_activation=activations[0]
model.input输出是正常的,问题出在keras 的model
models.Model()改为tf.keras.models.Model()输出正常
tu.PNG
网友评论