程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python 調用自己的跑出來的H5模型無法調用預測

編輯:Python

在主函數上我待用整體是可以跑的

主函數部分代碼

#分離數據集 訓練和驗證 以及類名#初始化mobilenetv2模型def get_MOBILENT_model(IMG_SHAPE=(224, 224, 3), class_num=245): # 微調的過程中不需要進行歸一化的處理 base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') # 加載mobilenetv2模型 base_model.trainable = False # 將主干的特征提取網絡參數進行凍結 model = tf.keras.models.Sequential([ tf.keras.layers.experimental.preprocessing.Rescaling(1. / 127.5, offset=-1, input_shape=IMG_SHAPE), # 歸一化處理,將像素值處理為-1到1之間 base_model, tf.keras.layers.GlobalAveragePooling2D(), # 全局平均池化 tf.keras.layers.Dense(class_num, activation='softmax'), # 設置最後的全連接層,用於分類 ]) model.summary() # 輸出模型信息 # 模型訓練 model.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy']) # 用於編譯模型,指定模型的優化器是adam優化器,模型的損失函數是交叉熵損失函數 return model # 返回模型def train_test_split(date_dir,height_size,width_size, batch_size): train_ds = tf.keras.preprocessing.image_dataset_from_directory( #文件目錄 date_dir, #標簽將被編碼為分類向量 label_mode='categorical', # 劃分比例 validation_split=0.2, # 劃分比例 # 訓練集 subset="training", seed=123, image_size=(height_size, width_size), # 批次大小 batch_size=batch_size) val_ds = tf.keras.preprocessing.image_dataset_from_directory( date_dir, label_mode='categorical', # 劃分比例 validation_split=0.2, # 驗證集 subset="validation", seed=123, image_size=(height_size, width_size), #批次大小 batch_size=batch_size) class_names = train_ds.class_names # 獲取數據集的類名 return train_ds, val_ds, class_names # 返回訓練集、驗證集和類名def test(Date_dir,H5_name): train_ds, val_ds, class_names = train_test_split(Date_dir, 224, 224, 4) model = tf.keras.models.load_model(H5_name) model.summary() # loss, accuracy = model.evaluate(val_ds) # print('test accuracy :', accuracy) pre=model.predict(val_ds) print(len(pre[0]))

但是測試單張圖片的時候不可以

img_path=r"D:\python Rubbish\rubbish data\images\img_4.jpg"model = load_model("D:\python Rubbish\mobilent.h5")model.summary()img=image.load_img(img_path,target_size=(224,224))img_tensor = image.img_to_array(img)img_tensor/=127.5print('該圖像的尺寸為:',img_tensor.shape)#之前模型設立了偏移img_tensor=img_tensor-1print(img_tensor)img_tensor=np.expand_dims(img_tensor,axis=0)prediction=model.predict(img_tensor)print(prediction)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved