herrDeng網內搜尋

自訂搜尋

Ads

2023年5月6日 星期六

python本機端使用訓練好Keras模型的實作

 
python本機端使用訓練好Keras模型的實作。ai機器學習辨識的程式實作要有兩個前提,一是硬體軟體,二是訓練好的模型。 
[ML python套件tensorflow-gpu keras軟體安裝說明]https://youtu.be/gEsLLIIAuGs 
[谷哥Teachable Machine訓練Keras模型操作人、貓、狗辨識]https://youtu.be/HbZ5hggMbio
Code請開:

套件匯入,觀看cuda相關部份

  1. print('Teachable Machine之訓練好的keras model實作python code辨識部份')
  2. !nvidia-smi
  3. from keras.models import load_model # TensorFlow is required for Keras to work
  4. import cv2
  5. import numpy as np
  6. import tensorflow as tf
  7. print(tf.__version__)
  8. import keras
  9. print(keras.__version__)
  10. print(tf.test.is_built_with_cuda)
  11. tf.config.list_physical_devices('GPU')
  12.  
  13. print('下面上傳converted_keras.zip &欲辨識圖檔要在圖片中央')

匯入model, labels

  1. #google colab加上files.upload
  2. #要unzip converted_keras.zip
  3. # Disable scientific notation for clarity
  4. np.set_printoptions(suppress=True)
  5. # Load the model
  6. model = load_model("keras_model.h5", compile=False)
  7. # Load the labels
  8. class_names = open("labels.txt", "r").readlines()
  9.  

測試0.jpg~5.jpg圖裁切、縮放、正則化、預測

  1. ims=[str(i)+'.jpg' for i in range(6)]
  2. for fn in ims:
  3. image = cv2.imread(fn)
  4. h, w, c=image.shape
  5. s=min(h,w)
  6. print(h, ',', w, ',s=',s)
  7. #圖片裁切成正方形切
  8. if w<=h:
  9. image=image[(h-w)//2:w+(h-w)//2, :, :]
  10. else:
  11. image=image[:, (w-h)//2:h+(w-h)//2, :]
  12. print(image.shape)
  13. # Resize the raw image into (224-height,224-width) pixels
  14. image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
  15. #這部份在google colab要修改
  16. cv2.imshow('image',image)
  17. cv2.setWindowTitle('image', fn)
  18. cv2.waitKey(0)
  19. # Make the image a numpy array and reshape it to the models input shape.
  20. image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)
  21. # Normalize the image array
  22. image = (image / 127.5) - 1
  23. # Predicts the model
  24. prediction = model.predict(image)
  25. index = np.argmax(prediction)
  26. class_name = class_names[index]
  27. confidence_score = prediction[0][index]
  28. print(prediction)
  29. # Print prediction and confidence score
  30. print("Class:", class_name[2:], end="")
  31. print("Confidence Score:", confidence_score * 100, "%")
  32. print('\n=================')

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章