欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

keras topN顯示,自編寫代碼案例

 更新時間:2020年07月03日 08:46:29   作者:姚賢賢  
這篇文章主要介紹了keras topN顯示,自編寫代碼案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

對于使用已經(jīng)訓練好的模型,比如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%

補充知識: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各種自編碼代碼

以上這篇keras topN顯示,自編寫代碼案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 將pip源更換到國內(nèi)鏡像的詳細步驟

    將pip源更換到國內(nèi)鏡像的詳細步驟

    這篇文章主要介紹了將pip源更換到國內(nèi)鏡像的詳細步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-04-04
  • 基于Python實現(xiàn)一個圖片壓縮工具

    基于Python實現(xiàn)一個圖片壓縮工具

    圖片壓縮是在保持圖像質(zhì)量的同時減小圖像文件大小的過程,本文將學習如何使用Python來實現(xiàn)一個簡單但功能強大的圖片壓縮工具,以及如何在不同情境下進行圖片壓縮,希望對大家有所幫助
    2024-01-01
  • Python和Anaconda和Pycharm安裝教程圖文詳解

    Python和Anaconda和Pycharm安裝教程圖文詳解

    PyCharm是一種PythonIDE,帶有一整套可以幫助用戶在使用Python語言開發(fā)時提高其效率的工具,這篇文章主要介紹了Python和Anaconda和Pycharm安裝教程,需要的朋友可以參考下
    2020-02-02
  • python利用datetime模塊計算時間差

    python利用datetime模塊計算時間差

    python中通過datetime模塊可以很方便的計算兩個時間的差,datetime的時間差單位可以是天、小時、秒,甚至是微秒,下面我們就來詳細看下datetime的強大功能吧
    2015-08-08
  • OpenCV圖像縮放之cv.resize()函數(shù)詳解

    OpenCV圖像縮放之cv.resize()函數(shù)詳解

    resize函數(shù)opencv中專門用來調(diào)整圖像大小的函數(shù),下面這篇文章主要給大家介紹了關(guān)于OpenCV圖像縮放之cv.resize()函數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-09-09
  • python深度學習tensorflow安裝調(diào)試教程

    python深度學習tensorflow安裝調(diào)試教程

    這篇文章主要為大家介紹了python深度學習tensorflow安裝調(diào)試教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Python實現(xiàn)分段線性插值

    Python實現(xiàn)分段線性插值

    這篇文章主要為大家詳細介紹了Python實現(xiàn)分段線性插值,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • 解決python 文本過濾和清理問題

    解決python 文本過濾和清理問題

    文本過濾和清理所涵蓋的范圍非常廣泛,涉及文本解析和數(shù)據(jù)處理方面的問題。這篇文章主要介紹了解決python 文本過濾和清理問題,需要的朋友可以參考下
    2019-08-08
  • vscode配置anaconda3的方法步驟

    vscode配置anaconda3的方法步驟

    這篇文章主要介紹了vscode配置anaconda3的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • Python數(shù)據(jù)可視化之Matplotlib和Seaborn的使用教程詳解

    Python數(shù)據(jù)可視化之Matplotlib和Seaborn的使用教程詳解

    這篇文章主要為大家詳細介紹了Python數(shù)據(jù)可視化中Matplotlib和Seaborn使用的相關(guān)教程,文中的示例代碼講解詳細,有需要的可以參考下
    2024-03-03

最新評論