keras topN顯示,自編寫代碼案例
對于使用已經(jīng)訓(xùn)練好的模型,比如VGG,RESNET等,keras都自帶了一個keras.applications.imagenet_utils.decode_predictions的方法,有很多限制:
def decode_predictions(preds, top=5):
"""Decodes the prediction of an ImageNet model.
# Arguments
preds: Numpy tensor encoding a batch of predictions.
top: Integer, how many top-guesses to return.
# Returns
A list of lists of top class prediction tuples
`(class_name, class_description, score)`.
One list of tuples per sample in batch input.
# Raises
ValueError: In case of invalid shape of the `pred` array
(must be 2D).
"""
global CLASS_INDEX
if len(preds.shape) != 2 or preds.shape[1] != 1000:
raise ValueError('`decode_predictions` expects '
'a batch of predictions '
'(i.e. a 2D array of shape (samples, 1000)). '
'Found array with shape: ' + str(preds.shape))
if CLASS_INDEX is None:
fpath = get_file('imagenet_class_index.json',
CLASS_INDEX_PATH,
cache_subdir='models',
file_hash='c2c37ea517e94d9795004a39431a14cb')
with open(fpath) as f:
CLASS_INDEX = json.load(f)
results = []
for pred in preds:
top_indices = pred.argsort()[-top:][::-1]
result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices]
result.sort(key=lambda x: x[2], reverse=True)
results.append(result)
return results
把重要的東西挖出來,然后自己敲,這樣就OK了,下例以MNIST數(shù)據(jù)集為例:
import keras
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import tflearn
import tflearn.datasets.mnist as mnist
def decode_predictions_custom(preds, top=5):
CLASS_CUSTOM = ["0","1","2","3","4","5","6","7","8","9"]
results = []
for pred in preds:
top_indices = pred.argsort()[-top:][::-1]
result = [tuple(CLASS_CUSTOM[i]) + (pred[i]*100,) for i in top_indices]
results.append(result)
return results
x_train, y_train, x_test, y_test = mnist.load_data(one_hot=True)
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=784))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, batch_size=128)
# score = model.evaluate(x_test, y_test, batch_size=128)
# print(score)
preds = model.predict(x_test[0:1,:])
p = decode_predictions_custom(preds)
for (i,(label,prob)) in enumerate(p[0]):
print("{}. {}: {:.2f}%".format(i+1, label,prob))
# 1. 7: 99.43%
# 2. 9: 0.24%
# 3. 3: 0.23%
# 4. 0: 0.05%
# 5. 2: 0.03%
補(bǔ)充知識:keras簡單的去噪自編碼器代碼和各種類型自編碼器代碼
我就廢話不多說了,大家還是直接看代碼吧~
start = time()
from keras.models import Sequential
from keras.layers import Dense, Dropout,Input
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPooling1D
from keras import layers
from keras.models import Model
# Parameters for denoising autoencoder
nb_visible = 120
nb_hidden = 64
batch_size = 16
# Build autoencoder model
input_img = Input(shape=(nb_visible,))
encoded = Dense(nb_hidden, activation='relu')(input_img)
decoded = Dense(nb_visible, activation='sigmoid')(encoded)
autoencoder = Model(input=input_img, output=decoded)
autoencoder.compile(loss='mean_squared_error',optimizer='adam',metrics=['mae'])
autoencoder.summary()
# Train
### 加一個early_stooping
import keras
early_stopping = keras.callbacks.EarlyStopping(
monitor='val_loss',
min_delta=0.0001,
patience=5,
verbose=0,
mode='auto'
)
autoencoder.fit(X_train_np, y_train_np, nb_epoch=50, batch_size=batch_size , shuffle=True,
callbacks = [early_stopping],verbose = 1,validation_data=(X_test_np, y_test_np))
# Evaluate
evaluation = autoencoder.evaluate(X_test_np, y_test_np, batch_size=batch_size , verbose=1)
print('val_loss: %.6f, val_mean_absolute_error: %.6f' % (evaluation[0], evaluation[1]))
end = time()
print('耗時:'+str((end-start)/60))
以上這篇keras topN顯示,自編寫代碼案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Keras 加載已經(jīng)訓(xùn)練好的模型進(jìn)行預(yù)測操作
這篇文章主要介紹了Keras 加載已經(jīng)訓(xùn)練好的模型進(jìn)行預(yù)測操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
keras的ImageDataGenerator和flow()的用法說明
這篇文章主要介紹了keras的ImageDataGenerator和flow()的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
python中Tkinter實(shí)現(xiàn)分頁標(biāo)簽的示例代碼
這篇文章主要介紹了python中Tkinter實(shí)現(xiàn)分頁標(biāo)簽的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
pandas 缺失值與空值處理的實(shí)現(xiàn)方法
這篇文章主要介紹了pandas 缺失值與空值處理的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
使用Python的toolz庫開始函數(shù)式編程的方法
這篇文章主要介紹了使用Python的toolz庫開始函數(shù)式編程的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11
Pandas統(tǒng)計計數(shù)value_counts()的使用
本文主要介紹了Pandas統(tǒng)計計數(shù)value_counts()的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Python使用QQ郵箱發(fā)送郵件實(shí)例與QQ郵箱設(shè)置詳解
這篇文章主要介紹了Python發(fā)送QQ郵件實(shí)例與QQ郵箱設(shè)置詳解,需要的朋友可以參考下2020-02-02

