我在MATLAB中调用Python代码时遇到问题。我的Python代码涉及使用LSTM预测电池充电状态,并基于MATLAB发送的输入进行注意力ANN。然后将预测发送回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)
这个错误看起来像是h5py没有被MATLAB识别,所以我尝试使用命令提示符重新安装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('5py'(",它帮助我解决了这个问题。以下是我的解决方案,供那些想参考的人使用:
当我在matlab代码中包含"py.importlib.import_module('5py'("时,我收到了以下错误:
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