keras 如何从这个集合模型中获得预测?

dsf9zpds  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(116)
# Load the hdf5 files
from keras.models import load_model

resnet50 = keras.models.load_model('/content/drive/MyDrive/HDF5 Files/RestNet 50 best_model.hdf5')
resnet152 = keras.models.load_model('/content/drive/MyDrive/HDF5 Files/best_model_4.hdf5')

# Get the predictions from each model
predictions1 = resnet50.predict(images)
predictions3 = resnet152.predict(images)

# Combine the predictions using a majority vote
predictions = np.array([predictions1,  predictions3])
predictions = np.mean(predictions, axis=0)
print(predictions)

。我得到的输出是9.9993783e-01 1.3912816e-06 6.0800008e-05 2.9077312e-09。这意味着什么?

k3fezbri

k3fezbri1#

从你的问题来看,你通过了多少张图片,以及你的问题中有多少个分类类别,这并不清楚。我将试着在一般意义上回答。
假设你将一批4个图像传递给模型restnet50resnet152,并且它们都在5个类别上训练,则每个模型将给予具有形状(4,5)的预测。

>> predictions1.shape
(4,5)
>> predictions3.shape
(4,5)

要将它们组合起来以获得多数票,您应该编写如下代码:

>>predictions = np.dstack((predictions1, predictions3)) # stack along the third axis.
>>predictions.shape
(4,5,2)
>> mean_predictions = np.mean(predictions, axis=2) # find the mean probabilities of both predictions in each category.
>> mean_predictions.shape
(4,5)
>> class_index = np.argmax(mean_predictions,axis=1) # Find the index having highest probability.
>> class_index.shape
(4,)

最后的class_index给出了4张图片中每一张图片所属的类或类别的索引。我希望这能有所帮助。

更好的方式您可以使用更好的方式在tensorflow 中创建集合模型,如下所示:

from tensorflow.keras.applications.resnet50 import preprocess_input as process_resnet50
from tensorflow.keras.applications.resnet150 import preprocess_input as process_resnet150
from tensorflow.keras.layers import Lambda,Dense,GlobalMaxPool2D,Concatenate
from tensorflow.keras import Input, Model
from keras.models import load_model

resnet50 = keras.models.load_model('/content/drive/MyDrive/HDF5 Files/RestNet 50 best_model.hdf5')
resnet152 = keras.models.load_model('/content/drive/MyDrive/HDF5 Files/best_model_4.hdf5')

category_count = 5 # you can give your own category count.
inp = Input(input_shape)
resnet_prep50 = tf.keras.layers.Lambda(process_resnet50)(inp)
res_net50 = resnet50(resnet_prep50)
x_resnet50 = GlobalMaxPool2D()(res_net50)
x_resnet50 = Dense(128, activation='relu')(x_resnet50)

resnet_prep150 = tf.keras.layers.Lambda(process_resnet150)(inp)
res_net150 = resnet152(resnet_prep150)
x_resnet150 = GlobalMaxPool2D()(res_net150)
x_resnet150 = Dense(128, activation='relu')(x_resnet150)

x = Concatenate()([x_resnet50, x_resnet150])
out = Dense(category_count, activation='softmax')(x)

ensemble_model = Model(inputs=inp, outputs = out)
predictions = ensemble_model.predict(images)
predictions = np.argmax(predictions, axis=1)

相关问题