Problem When exporting matlab model to tensorflow in Python

28 ビュー (過去 30 日間)
Muhammad Durrani Hakim  Bin Mohd Fared
Muhammad Durrani Hakim Bin Mohd Fared 2024 年 3 月 28 日 6:04
コメント済み: Shivansh 2024 年 4 月 1 日 6:46
Hi,
Recently I discovered that we can export the MATLAB code to tensorflow using this syntax
exportNetworkToTensorFlow(net,modelPackage)
I have succesfully exported it to tensor flow and they gave me a file which I named "TestPythonDSP" which contained two python file(_init_.py and model.py) and one hdf5 file (weights.h5)
I tried to run the code on VSC but only error. I would like to know what should I do after this and where can I test the tensorflow model. Any help and opinion would be very helpful
I plan to Load the exported TensorFlow model with weights in Python @ Raspberry Pi
%model.py
# This file was created by
# MATLAB Deep Learning Toolbox Converter for TensorFlow Models.
# 28-Mar-2024 12:57:25
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def create_model():
imageinput_unnormalized = keras.Input(shape=(98,50,1), name="imageinput_unnormalized")
imageinput = keras.layers.Normalization(axis=(1,2,3), name="imageinput_")(imageinput_unnormalized)
conv_1 = layers.Conv2D(12, (3,3), padding="same", name="conv_1_")(imageinput)
batchnorm_1 = layers.BatchNormalization(epsilon=0.000010, name="batchnorm_1_")(conv_1)
relu_1 = layers.ReLU()(batchnorm_1)
maxpool_1 = layers.MaxPool2D(pool_size=(3,3), strides=(2,2), padding="same")(relu_1)
conv_2 = layers.Conv2D(24, (3,3), padding="same", name="conv_2_")(maxpool_1)
batchnorm_2 = layers.BatchNormalization(epsilon=0.000010, name="batchnorm_2_")(conv_2)
relu_2 = layers.ReLU()(batchnorm_2)
maxpool_2 = layers.MaxPool2D(pool_size=(3,3), strides=(2,2), padding="same")(relu_2)
conv_3 = layers.Conv2D(48, (3,3), padding="same", name="conv_3_")(maxpool_2)
batchnorm_3 = layers.BatchNormalization(epsilon=0.000010, name="batchnorm_3_")(conv_3)
relu_3 = layers.ReLU()(batchnorm_3)
maxpool_3 = layers.MaxPool2D(pool_size=(3,3), strides=(2,2), padding="same")(relu_3)
conv_4 = layers.Conv2D(48, (3,3), padding="same", name="conv_4_")(maxpool_3)
batchnorm_4 = layers.BatchNormalization(epsilon=0.000010, name="batchnorm_4_")(conv_4)
relu_4 = layers.ReLU()(batchnorm_4)
conv_5 = layers.Conv2D(48, (3,3), padding="same", name="conv_5_")(relu_4)
batchnorm_5 = layers.BatchNormalization(epsilon=0.000010, name="batchnorm_5_")(conv_5)
relu_5 = layers.ReLU()(batchnorm_5)
maxpool_4 = layers.MaxPool2D(pool_size=(13,1), strides=(1,1))(relu_5)
dropout = layers.Dropout(0.200000)(maxpool_4)
fc = layers.Reshape((-1,), name="fc_preFlatten1")(dropout)
fc = layers.Dense(12, name="fc_")(fc)
softmax = layers.Softmax()(fc)
model = keras.Model(inputs=[imageinput_unnormalized], outputs=[softmax])
return model
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
%_init_.py file
# This file was created by
# MATLAB Deep Learning Toolbox Converter for TensorFlow Models.
# 28-Mar-2024 12:57:25
import TestPythonDSP.model
model = TestPythonDSP.load_model()
import os
def load_model(load_weights=True, debug=False):
m = model.create_model()
if load_weights:
loadWeights(m, debug=debug)
return m
## Utility functions:
import tensorflow as tf
import h5py
def loadWeights(model, filename=os.path.join(__package__, "weights.h5"), debug=False):
with h5py.File(filename, 'r') as f:
# Every layer is an h5 group. Ignore non-groups (such as /0)
for g in f:
if isinstance(f[g], h5py.Group):
group = f[g]
layerName = group.attrs['Name']
numVars = int(group.attrs['NumVars'])
if debug:
print("layerName:", layerName)
print(" numVars:", numVars)
# Find the layer index from its namevar
layerIdx = layerNum(model, layerName)
layer = model.layers[layerIdx]
if debug:
print(" layerIdx=", layerIdx)
# Every weight is an h5 dataset in the layer group. Read the weights
# into a list in the correct order
weightList = [0]*numVars
for d in group:
dataset = group[d]
varName = dataset.attrs['Name']
shp = intList(dataset.attrs['Shape'])
weightNum = int(dataset.attrs['WeightNum'])
# Read the weight and put it into the right position in the list
if debug:
print(" varName:", varName)
print(" shp:", shp)
print(" weightNum:", weightNum)
weightList[weightNum] = tf.constant(dataset[()], shape=shp)
# Assign the weights into the layer
for w in range(numVars):
if debug:
print("Copying variable of shape:")
print(weightList[w].shape)
layer.variables[w].assign(weightList[w])
if debug:
print("Assignment successful.")
print("Set variable value:")
print(layer.variables[w])
# Finalize layer state
if hasattr(layer, 'finalize_state'):
layer.finalize_state()
def layerNum(model, layerName):
# Returns the index to the layer
layers = model.layers
for i in range(len(layers)):
if layerName==layers[i].name:
return i
print("")
print("WEIGHT LOADING FAILED. MODEL DOES NOT CONTAIN LAYER WITH NAME: ", layerName)
print("")
return -1
def intList(myList):
# Converts a list of numbers into a list of ints.
return list(map(int, myList))
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  1 件のコメント
Shivansh
Shivansh 2024 年 4 月 1 日 6:46
Hi Muhammad,
It seems like you are facing some issues with the generated python files from "exportNetworkToTensorFlow" method. It won't be possible to suggest anything without reproducing the issue using the network "net". It will be helpful if you can share the reproduction steps as well as error message you are getting on running the files on VS Code.

サインインしてコメントする。

回答 (0 件)

製品


リリース

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by