日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

evaluate函数使用无效_在Matlab中使用tensorflow (2)

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 evaluate函数使用无效_在Matlab中使用tensorflow (2) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本篇介紹如何在matlab中調用python訓練好的網絡模型和權重。

系統環境:win10,matlab2018b,python3.6,tensorflow1.1

代碼如下:

tf = py.importlib.import_module('tensorflow'); np = py.importlib.import_module('numpy'); plt = py.importlib.import_module('matplotlib.pyplot'); sio = py.importlib.import_module('scipy.io'); run = py.importlib.import_module('run'); py.importlib.reload(run); % 載入數據 loaddata = run.load_data(); % train_images = double(loaddata{1}); % 載入訓練數據 % train_labels = double(loaddata{2}); test_images = double(loaddata{3}); % 載入測試數據 test_labels = double(loaddata{4}); % 載入訓練好的模型 model = run.create_model(); model.load_weights("training_1/cp.ckpt"); %% 使用 idx_sel = [1:39]; image_use = cell([1,length(idx_sel)]); labels_use = zeros(1,length(idx_sel)); for i = 1:20% 測試用例:如果從matlab傳參到直接調用keras模型中的fit方法會報錯,image_use = np.array(reshape(test_images(idx_sel(i),:,:),[1,28,28]));label_true = test_labels(idx_sel(i));% 執行預測label_pred = int64(model.predict_classes(image_use));% 顯示結果subplot(4,5,i)image_use_matlab = reshape(double(image_use),[28,28]); % 轉換成matlab格式的imageimshow(image_use_matlab)if label_pred == label_truetitle(['預測',num2str(label_pred),',真實',num2str(label_true)],'color','g') elsetitle(['預測',num2str(label_pred),',真實',num2str(label_true)],'color','r') end end

說明:

1)run是當前文件夾下的python文件,是tensorflow官網例子,實現手寫數字識別,訓練完成后對模型進行保存,以便在matlab中調用。run.py內容如下:

import tensorflow as tf from tensorflow import keras import numpy as np import scipy.io as sio #import matplotlib.pyplot as plt import osdef create_model():model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),keras.layers.Dense(128, activation=tf.nn.relu),keras.layers.Dense(10, activation=tf.nn.softmax)])model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy']) return modeldef load_data():path='./mnist.npz' f = np.load(path) with np.load(path) as f:train_images, train_labels = f['x_train'], f['y_train'] test_images, test_labels = f['x_test'], f['y_test'] return train_images, train_labels, test_images, test_labelsdef train():train_images, train_labels, test_images, test_labels = load_data() train_images = np.array(train_images)train_labels = np.array(train_labels)test_images = np.array(test_images)test_labels = np.array(test_labels)train_images = train_images / 255.0test_images = test_images / 255.0#plt.figure(figsize=(10,10))#for i in range(25):# plt.subplot(5,5,i+1)# plt.xticks([])# plt.yticks([])# plt.grid(False)# plt.imshow(train_images[i], cmap=plt.cm.binary)# plt.xlabel(class_names[train_labels[i]])#plt.show()checkpoint_path = "training_1/cp.ckpt"checkpoint_dir = os.path.dirname(checkpoint_path)# Create checkpoint callbackcp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,save_weights_only=True,verbose=1)model = create_model()model.fit(train_images, train_labels, epochs=5,callbacks=[cp_callback])test_loss, test_acc = model.evaluate(test_images, test_labels)print('Test accuracy:', test_acc)predictions = model.predict(test_images)return modelif __name__ == '__main__':train_images, train_labels, test_images, test_labels = load_data()model = train()

2)使用流程:

  • 下載mnist數據集
  • 運行run.py進行訓練并保存訓練結果
  • 運行matlab函數,在matlab中調用python中訓練的模型進行推理,結果如下

3)matlab中調用python sys模塊中的方法屬性會出問題,而keras的fit方法會調用到sys.stdout.flush等方法,因此不能由matlab調用含相關方法的python函數,例如model.fit,model.evaluate等,但model.predict等能夠直接在matlab中使用

4)本篇內容僅是對matlab中調用python的一個說明,該方式并不是實現諸如手寫數字識別的最佳方式。如果要在matlab中進行相關功能開發,使用matlab深度學習工具箱更加方便;此外matlab也支持onnx轉換的模型。

總結

以上是生活随笔為你收集整理的evaluate函数使用无效_在Matlab中使用tensorflow (2)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。