[英]Issue with opening h5 file with Python code in MATLAB environment
我在 MATLAB 中調用 Python 代碼時遇到問題。 我的 Python 代碼涉及基於從 MATLAB 發送的輸入,使用帶有注意力神經網絡的 LSTM 預測電池充電狀態。 然后將預測發送回 MATLAB。 我之前已經將訓練好的權重和偏差保存在一個 h5 文件中,該文件在 Python 代碼中加載和使用。 下面是 Python 代碼:
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from tensorflow import keras
from tensorflow.keras import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
from tensorflow.keras import optimizers
import matplotlib.pyplot as plt
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
from tensorflow.keras import backend as K
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Dropout, InputLayer
import h5py
#to create sequential data
def create_inout_sequences(input_data, tw):
inout_seq = []
L = len(input_data)
for i in range(L-tw):
train_seq = input_data[i:i+tw]
#train_out = output_data[i:i+tw]
inout_seq.append(train_seq)
return inout_seq
def search(inputs):
class attention(Layer):
def __init__(self, return_sequences=True,**kwargs):
self.return_sequences = return_sequences
super(attention,self).__init__()
def build(self, input_shape):
self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
initializer="normal")
self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
initializer="zeros")
super(attention,self).build(input_shape)
def call(self, x):
e=(K.dot(x,self.W)+self.b)
a = K.softmax(e, axis=1)
output = x*a
if self.return_sequences:
return output
return K.sum(output, axis=1)
def get_config(self):
# For serialization with 'custom_objects'
config = super().get_config()
config['return_sequences'] = self.return_sequences
return config
#convert test data to sequential form
inputs=np.array(inputs)
inputs=np.tile(inputs, (36, 1))
inputs_new=create_inout_sequences(inputs, 35)
inputs_new=np.array(inputs_new)
model1 = Sequential()
model1.add(InputLayer(input_shape=(35,5)))
model1.add((LSTM(22, return_sequences=True)))
model1.add(attention(return_sequences=False))
model1.add(Dense(104, activation="relu"))
model1.add(Dropout(0.2))
model1.add(Dense(1, activation="sigmoid"))
lr_schedule = keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.01,
decay_steps=10000,
decay_rate=0.99)
model1.compile(optimizer=tf.keras.optimizers.Adam(epsilon=1e-08,learning_rate=lr_schedule),loss='mse')
#call previously trained weights
model1.load_weights('SOC_weights.h5')
x=float(model1.predict(inputs_new, batch_size=100,verbose=0))
return x # send prediction to Matlab
注意:我使用的是 Python 3.6,tensorflow 版本:2.5,keras 版本:2.4.3,h5py 版本:3.1.0,cython 版本:0.28
我能夠在 Python 上運行此代碼而不會出現任何錯誤,但是在 MATLAB 2020a 中使用時出現問題......下面是我的 MATLAB 代碼:
pyenv('Version','3.6');
py.importlib.import_module('tensorflow');
py.importlib.import_module('testingSOC'); % file containing the Python codes
inputs=[0.555555556,0.435139205,0.68313128,0.499987472,0.241225578];% test inputs
SOC_output=py.testingSOC.search(inputs)
以下是在 Matlab 上收到的錯誤:
Error using training>load_weights (line 2312)
Python Error: ImportError: `load_weights` requires h5py when loading weights from HDF5.
Error in testingSOC>search (line 87)
該錯誤看起來像 MATLAB 未識別出 h5py,因此我嘗試使用命令提示符重新安裝 h5py(我使用的是 Windows 10):
pip uninstall h5py
pip install h5py
但沒有變化...
我也嘗試過 tensorflow 版本:2.2、keras 版本 2.4.3、h5py 版本 2.10 和 cython 版本 0.29,但仍然出現相同的錯誤。
如果你們能提供解決此問題的見解,以及我遺漏的任何基本部分,我將不勝感激。 如果需要,我很樂意分享更多細節。
謝謝!
感謝@TimRoberts 指出包含 'py.importlib.import_module('h5py')' 這幫助我解決了這個問題。以下是我的解決方案,供想參考的人參考:
當我在我的 matlab 代碼中包含 'py.importlib.import_module('h5py')' 時,我收到以下錯誤:
Error using h5>init h5py.h5 (line 1)
Python Error: ImportError: DLL load failed: The specified procedure could not be found.
在我的例子中,看起來 Python 環境似乎使用了 Matlab 的 h5 庫,它與 Python 的 h5 庫沒有相同的功能......我發現有一個選項可以將 Python 代碼作為一個單獨的進程運行,這似乎是為我(如本鏈接所示): https : //www.mathworks.com/help/matlab/matlab_external/out-of-process-execution-of-python-functionality.html?searchHighlight=out%20of%20process%20python&s_tid =srchtitle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.