首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MATLAB环境下用Python代码打开h5文件的问题

在MATLAB环境下用Python代码打开h5文件的问题
EN

Stack Overflow用户
提问于 2021-07-12 23:59:01
回答 1查看 77关注 0票数 0

我在MATLAB中调用Python代码时遇到了问题。然后,预测结果被发送回MATLAB。以下是Python代码:

代码语言:javascript
复制
    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

注意:我使用的是Python3.6,tensorflow版本: 2.5,keras版本: 2.4.3,h5py版本: 3.1.0,cython版本: 0.28

我能够在Python上运行此代码而没有任何错误,但在MATLAB 2020a中使用时有问题...下面是我的MATLAB代码:

代码语言:javascript
复制
   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上收到的错误:

代码语言:javascript
复制
    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 (我使用的是Windows10):

代码语言:javascript
复制
    pip uninstall h5py
    pip install h5py

但是没有任何改变。

我也尝试过tensorflow版本: 2.2,keras版本2.4.3,h5py版本2.10和cython版本0.29,但仍然得到相同的错误。

如果你们能提供解决这个问题的洞察力,以及是否有任何我遗漏的基本部分,我将非常感激。如果需要的话,我很乐意分享更多的细节。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-07-13 21:40:54

感谢@TimRoberts指出包括'py.importlib.import_module('h5py')‘,它帮助我解决了这个issue.Below,对于那些想要参考的人来说,这是我的解决方案:

当我在matlab代码中包含'py.importlib.import_module('h5py')‘时,我收到以下错误:

代码语言:javascript
复制
    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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68350444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档