New Ribbon
Canva+AI創意設計與品牌應用250招:從商業技巧、社群祕技到AI圖文影音特效 快快樂樂學威力導演2024.影音剪輯與AI精彩創作 文淵閣工作室祝福大家新年快樂.龍年吉祥 Power Automate自動化超效率工作術 Midjourney AI圖像魔導書:搭配ChatGPT魔法加倍 超人氣FB+IG+LINE社群經營與行銷力(第二版) 翻倍效率工作術:不會就太可惜的 Excel × ChatGPT 自動化應用 AppInventor2零基礎入門班中文版(第六版) Python零基礎入門班(第四版) C語言學習聖經 用Canva設計超快超質感:平面、網頁、電子書、簡報、影片製作與AI繪圖最速技 PHP8/MySQL網頁程式設計自學聖經 翻倍效率工作術 - 不會就太可惜的Power BI大數據視覺圖表設計與分析(第三版) 社群經營一定要會的影音剪輯與動畫製作術 Notion高效管理250招:筆記×資料庫×團隊協作,數位生活與工作最佳幫手 Office 2021高效實用範例必修16課(附500分鐘影音教學/範例檔) Excel自學聖經(第二版):從完整入門到職場活用的技巧與實例大全 網路開店×拍賣王:蝦皮來了(第二版) 專家都在用的Google最強實戰:表單、文件、試算、簡報、遠距與線上會議 超人氣 Instagram 視覺行銷力(第二版):小編不敗,經營 IG 品牌人氣王的 120 個秘技!

 

  Python自學聖經_模型儲存與預測

Oscar

Oscar
更新時間:2022/8/2 下午 01:46:06

 

在24-22頁,預測自製數字圖片內使用Mnist_Predict.py,出現以下錯誤

import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
import glob,cv2

def show_images_labels_predictions(images,labels,predictions,start_id,num=10):
    plt.gcf().set_size_inches(12, 14)
    if num>25: num=25
    for i in range(0, num):
        ax=plt.subplot(5,5, i+1)
        ax.imshow(images[start_id], cmap='binary')  #顯示黑白圖片
        if( len(predictions) > 0 ) :  #有傳入預測資料
            title = 'ai = ' + str(predictions[start_id])
            # 預測正確顯示(o), 錯誤顯示(x)
            title += (' (o)' if predictions[start_id]==labels[start_id] else ' (x)')
            title += '\nlabel = ' + str(labels[start_id])
        else :  #沒有傳入預測資料
            title = 'label = ' + str(labels[start_id])
        ax.set_title(title,fontsize=12)  #X,Y軸不顯示刻度
        ax.set_xticks([]);ax.set_yticks([])        
        start_id+=1
    plt.show()
    
files = glob.glob("imagedata\*.jpg")  #建立測試資料
test_feature=[]
test_label=[]
for file in files:
    img=cv2.imread(file)
    img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  #灰階    
    _, img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY_INV) #轉為反相黑白
    test_feature.append(img)
    label=file[10:11]  #"imagedata\1.jpg"第10個字元1為label
    test_label.append(int(label))
  
test_feature=np.array(test_feature) # 串列轉為矩陣
test_label=np.array(test_label)     # 串列轉為矩陣
test_feature_vector = test_feature.reshape(len( test_feature), 784).astype('float32')
test_feature_normalize = test_feature_vector/255
model = load_model('Mnist_mlp_model.h5')

#prediction=model.predict_classes(test_feature_normalize)
predict_x=model.predict(test_feature_normalize)
prediction=np.argmax(predict_x,axis=1)  #預測
show_images_labels_predictions(test_feature,test_label,prediction,0,len(test_feature))

因為model.predict_classes已例停用,使用predict_x=model.predict(test_feature_normalize)
prediction=np.argmax(predict_x,axis=1)取代

但執行後出現以下錯誤:
2022-08-02 13:18:52.197306: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "/Users/meiwa/Learning/Python/Machine_Learning/Mnist_Predict.py", line 42, in <module>
    predict_x=model.predict(test_feature_normalize)
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/engine/training.py", line 2048, in predict
    raise ValueError('Unexpected result of `predict_function` '
ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

文淵閣工作室

文淵閣工作室
更新時間:2022/8/2 下午 08:07:06

 

請將41列程式「prediction=model.predict_classes(test_feature_normalize)」改為:
prediction=model.predict(test_feature_normalize)
prediction=np.argmax(prediction,axis=1)

Oscar

Oscar
更新時間:2022/8/3 上午 10:50:42

 

出現以下錯誤:
2022-08-03 10:49:17.879632: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "/Users/meiwa/Learning/Python/Machine_Learning/Mnist_Predict.py", line 42, in <module>
    prediction=model.predict(test_feature_normalize)
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/engine/training.py", line 2048, in predict
    raise ValueError('Unexpected result of `predict_function` '
ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

文淵閣工作室

文淵閣工作室
更新時間:2022/8/3 下午 06:38:48

 

看起來您的程式碼已修正,請自行搜尋關鍵字
「To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.」
看是否可找到解決。

這一篇您先參考:
https://stackoverflow.com/questions/66092421/how-to-rebuild-tensorflow-with-the-compiler-flags

如果仍不行,建議不要在虛擬環境執行,改在正常的環境試試看。

Oscar

Oscar
更新時間:2022/8/3 下午 10:22:01

 

謝謝,參考了你提供的文章後,在程式加了以下句子:
import os
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
以下錯誤消失了
2022-08-03 21:45:56.371070: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

但程式還是不能成功運行

Traceback (most recent call last):
  File "/Users/meiwa/Learning/Python/Machine_Learning/Mnist_Predict.py", line 45, in <module>
    prediction=model.predict(test_feature_normalize)
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/Users/meiwa/Learning/Python/Machine_Learning/.venv/lib/python3.10/site-packages/keras/engine/training.py", line 2048, in predict
    raise ValueError('Unexpected result of `predict_function` '
ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

我想這是因為empty input array in Model.fit function? 但找不到解決方法。

是不是有關硬件及版本問題?

OS: macOS Monterey ver12.3
tensorflow==2.9.1
tensorflow-estimator==2.9.0
tensorflow-io-gcs-filesystem==0.26.0
keras==2.9.0
Keras-Preprocessing==1.1.2

Oscar

Oscar
更新時間:2022/8/3 下午 10:29:26

 

我在最後的位置加了

print(test_feature_normalize)

result:
[]

文淵閣工作室

文淵閣工作室
更新時間:2022/8/4 上午 08:45:00

 

感覺好像是沒有讀取到圖檔。

請將路徑『\』改為『/』,即:
files = glob.glob("imagedata/*.jpg")

Oscar

Oscar
更新時間:2022/8/4 下午 12:35:06

 

謝謝,是沒有讀到圖案

將路徑『\』改為『/』後,可以運行了

但想了解一下『\』和『/』的分別,和使用方法,有網站可以參考和學習嗎?謝謝

文淵閣工作室

文淵閣工作室
更新時間:2022/8/4 下午 05:34:45

 

因為您的電腦是 mac,linux 系統的路徑符號是「/」,而我們書籍的環境是 windows,路徑符號是「\」。

Oscar

Oscar
更新時間:2022/8/5 下午 12:44:33

 

了解,謝謝

瑞展

瑞展
更新時間:2022/10/7 下午 02:46:53

 

修改41列程式後,在「Mnist_loadModel1.py」這個範例能執行,但「Mnist_Predict.py」在虛擬環境中一直顯示如下錯誤,改以正常環境才執行成功,請問有無修正方式。

ValueError: Unexpected result of `predict_function` (Empty batch_outputs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

瑞展

瑞展
更新時間:2022/10/7 下午 02:50:28

 

在正常環境執行一次後,又能在虛擬環境執行了




 

 

Re:Python自學聖經_模型儲存與預測

請輸入姓名。

已超出字元數目的最大值。


請輸入電子郵件。

格式無效。


請輸入內容。