【发布时间】:2021-03-12 12:03:39
【问题描述】:
我有以下代码,我需要删除模型的一些层并执行预测。但目前我正在检索错误。
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
from keras.models import Model
from tensorflow.python.keras.optimizers import SGD
base_model = ResNet50(include_top=False, weights='imagenet')
model= Model(inputs=base_model.input, outputs=base_model .layers[-2].output)
#model = Model(inputs=base_model.input, outputs=predictions)
#Compiling the model
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics =
['accuracy'])
img_path = 'elephant.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])
错误
File "C:/Users/learn/remove_layer.py", line 9, in <module>
model= Model(inputs=base_model.input, outputs=base_model .layers[-2].output)
AttributeError: 'Tensor' object has no attribute '_keras_shape'
由于我对 Keras 的初学者知识,我理解的是形状问题。由于它是一个 resnet 模型,如果我将一个层从一个合并删除到另一个合并层,因为合并层没有维度问题,我该如何完成呢?
【问题讨论】:
-
在您的导入中,您正在混合 tf.keras 和 keras,这不是一个好主意。
标签: tensorflow machine-learning keras tf.keras