Giter VIP home page Giter VIP logo

keras2ncnn's Introduction

It's Hanxiao!

EE major in Rose-Hulman Institute of Technology.

Research on edge computing, hardware-aware NAS, power/latency/energy predictors.

Hanxiao's GitHub stats

keras2ncnn's People

Contributors

marstechhan avatar zhiqwang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

keras2ncnn's Issues

Wrong classification model output

Converted model from keras to NCNN. Pre-processing used in keras(python) is as follows

# reading image in cv Mat format
orig = cv2.imread('black.png')
# Converting image from BGR to RGB
image = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
# Resizing image to 128x128
image = cv2.resize(image, (128, 128))
# Convert image to float by and normalize by dividing it by 255
image = image.astype("float") / 255.0
# Convert image to array
image = img_to_array(image)
# Expand numpy array dimentions
image = np.expand_dims(image, axis=0)
# Load keras model
model = tf.keras.models.load_model('cnn128.h5')
# Give input to keras model
pred = model.predict(image)[0]

I tried to replicate the steps in c++ for NCNN model

// reading image in cv Mat format
Mat image = imread("eyes.jpg"); //read image
// Converting image from BGR to RGB
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
// Resizing image to 128x128
Mat img;   
resize(image, img, Size(128, 128));
// Convert image to float by and normalize by dividing it by 255
img.convertTo(img,CV_32F);
img /= 255.0;
// Load ncnn model
ncnn::Net smallCNN;
smallCNN.load_param("cnn128.param");
smallCNN.load_model("cnn128.bin");
// converting cv::Mat image to ncnn::Mat
ncnn::Mat in = ncnn::Mat::from_pixels(img.data, ncnn::Mat::PIXEL_RGB, img.cols, img.rows);
// Give input to ncnn model
ncnn::Extractor ex = smallCNN.create_extractor();
ex.input("conv2d_8_input_blob", in);

when run the code, as an output I am getting this value

8 = 1.000000
7 = 0.000000
6 = 0.000000

where 8 is the label and 1.000000 is the probability. correct label is 0 and not 8

can anyone please help to understand what went wrong in input processing ?

"list index out of range" Error for one layer network

model = Sequential()
model.add(Conv2D(3, (1,1), padding = 'valid',input_shape = (4, 4, 1), use_bias=False));

convert this model will trigger the error:

Start emitting to ncnn files.
Traceback (most recent call last):
  File "/home/bits/anaconda3/envs/py374_tf21/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/bits/anaconda3/envs/py374_tf21/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/bits/anaconda3/envs/py374_tf21/lib/python3.7/site-packages/keras2ncnn/__main__.py", line 12, in <module>
    sys.exit(_main())
  File "/home/bits/anaconda3/envs/py374_tf21/lib/python3.7/site-packages/keras2ncnn/keras2ncnn.py", line 81, in main
    graph_seq = emitter.get_graph_seq()
  File "/home/bits/anaconda3/envs/py374_tf21/lib/python3.7/site-packages/keras2ncnn/ncnn_emitter.py", line 18, in get_graph_seq
    q = [graph_head[0]]
IndexError: list index out of range

Please fix it xiaoxiao!

转换问题

你好,谢谢你的分享,我通过你的代码将一个h5模型转换成了ncnn模型,但有一个问题,生成的param文件各个层的顺序是乱的(虽然通过netron软件打开模型是正确的),请问有什么方法可以解决吗?谢谢

An issue in model conversion

Hello
How are you?
Thanks for contributing this project.
I met an issue when converting the vggface2 model, which is based on ResNet50 model.

image

I tried this conversion on both tf1.x and tf2.x but failed.
I send the source Keras model.
https://we.tl/t-MjAHF2SPiK
Please fix the issue asap.
Thanks

AttributeError: 'str' object has no attribute 'decode'

I tried to convert my model:
python3 -m keras2ncnn -i HOME.h5 -o .
But it reports issues like this:
(ncnn) micang@micang-X3:~$ python3 -m keras2ncnn -i HOME.h5 -o ./
Reading and parsing keras h5df file...
Traceback (most recent call last):
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/main.py", line 12, in
sys.exit(_main())
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/keras2ncnn.py", line 55, in main
H5dfParser(args.input_file).parse_graph(keras_graph)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/h5df_parser.py", line 10, in init
self.model_config = json.loads(model_config_raw.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'

After i upgrade my keras2ncnn to vertion 0.1.4, it still happens:
2021.02.10
(ncnn) micang@micang-X3:~$ python3 -m keras2ncnn -i HOME.h5 -o ./
Reading and parsing keras h5df file...
Traceback (most recent call last):
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/main.py", line 12, in
sys.exit(_main())
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/keras2ncnn.py", line 55, in main
H5dfParser(args.input_file).parse_graph(keras_graph)
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/h5df_parser.py", line 40, in init
self.keras_version = self.get_keras_version()
File "/home/micang/anaconda3/envs/ncnn/lib/python3.7/site-packages/keras2ncnn/h5df_parser.py", line 59, in get_keras_version
.attrs['keras_version'].decode('utf8')
AttributeError: 'str' object has no attribute 'decode'

转换MBLLEN keras 的模型后运行demo后出来的 out结果不对劲

你好,使用作者的工程成功完成了模型转化,但是在demo上跑起来的时候发现结果变成了花屏,正常应该是原图像的提亮图像。

使用netron打开了keras和ncnn模型,除了输入层从一个1hw3变成hw*3后就是下面每一层的输入尺寸都从abcd变成dcba,想问一下这个对结果有影响吗?如果有影响需要怎么修改呢?
image
image

期待作者大大的回复

relu6 bug

I find a bug in the relu6 activation

image

AttributeError: 'NoneType' object has no attribute 'decode'

Error: numpy alias `float` is deprecated

python -m keras2ncnn -i path/to/my/model.h5 -o ./
Reading and parsing keras h5df file...
Start graph optimizing pass...
	Removing unused nodes...
	Removing squeeze reshape after pooling...
	Refreshing graph...
Converting keras graph to ncnn graph...
Traceback (most recent call last):
  File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/mek101/.local/lib/python3.10/site-packages/keras2ncnn/__main__.py", line 12, in <module>
    sys.exit(_main())
  File "/home/mek101/.local/lib/python3.10/site-packages/keras2ncnn/keras2ncnn.py", line 69, in main
    KerasConverter().parse_keras_graph(keras_graph, ncnn_graph, NcnnParamDispatcher())
  File "/home/mek101/.local/lib/python3.10/site-packages/keras2ncnn/keras_converter.py", line 1412, in parse_keras_graph
    eval(
  File "/home/mek101/.local/lib/python3.10/site-packages/keras2ncnn/keras_converter.py", line 478, in BatchNormalization_helper
    bn_params['bn_beta'] = np.full([num_output, ], 0, dtype=np.float)
  File "/home/mek101/.local/lib/python3.10/site-packages/numpy/__init__.py", line 305, in __getattr__
    raise AttributeError(__former_attrs__[attr])
AttributeError: module 'numpy' has no attribute 'float'.
`np.float` was a deprecated alias for the builtin `float`. To avoid this error in existing code, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
    https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations. Did you mean: 'cfloat'?

'NoneType' object has no attribute 'decode'

你好,感谢贡献,感谢开源!我尝试转ckpt 模型至ncnn, 先将ckpt 转为了 .h5, 再使用你的方法转为ncnn , 在转的时候,报错如下:

Traceback (most recent call last):
File "keras2ncnn.py", line 1477, in
H5dfParser(args.input_file).parse_graph(keras_graph)
File "keras2ncnn.py", line 52, in init
self.model_config = json.loads(model_config_raw.decode('utf-8'))
AttributeError: 'NoneType' object has no attribute 'decode'

model_config_raw 读出来为空,可以帮忙看下吗 ? 链接是我的 h5(out.h5) 文件 和 ckpt 转换后的pb(freeze_538000.pb)文件(pb测试过没问题),其余两个文件请忽略

https://github.com/weilanShi/caffemodel

KeyError: 'attr'

运行 python -m keras2ncnn -i weights.h5 -o ./
出现

Reading and parsing keras h5df file...
Start graph optimizing pass...
Removing unused nodes...
Traceback (most recent call last):
File "D:\Anaconda3\envs\tf2-gpu\lib\runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "D:\Anaconda3\envs\tf2-gpu\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "D:\Anaconda3\envs\tf2-gpu\lib\site-packages\keras2ncnn_main
.py", line 12, in
sys.exit(_main())
File "D:\Anaconda3\envs\tf2-gpu\lib\site-packages\keras2ncnn\keras2ncnn.py", line 60, in main
GraphOptimization.removing_unused_nodes(keras_graph)
File "D:\Anaconda3\envs\tf2-gpu\lib\site-packages\keras2ncnn\graph_optimizer.py", line 9, in removing_unused_nodes
if graph.get_node_attr(target_node_name)[
File "D:\Anaconda3\envs\tf2-gpu\lib\site-packages\keras2ncnn\graph_tool.py", line 103, in get_node_attr
return self.graph[name]['attr']
KeyError: 'attr'

Debug mode error

I use python3 -m keras2ncnn -i model.h5 -o ./ -d in command for debugging the output inconsistent with keras
But I got error below, and I can't find keras2ncnn.cpp in the github web.
Where should i download this file?
Thanks

Reading and parsing keras h5df file...
Start graph optimizing pass...
        Removing unused nodes...
        Removing squeeze reshape after pooling...
        Refreshing graph...
Converting keras graph to ncnn graph...
Start emitting to ncnn files.
        Emitting param...
        Emitting binary...
Running accuracy matcher...
        Initing Env...
Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com
Requirement already satisfied: virtualenv==16.7.9 in /tools/software/anaconda3-4.4.0/envs/py3.7-tzuyun/lib/python3.6/site-packages (16.7.9)
        cmake is not inside PATH, please install it first.
        Preparing File...
        Generting File...
Traceback (most recent call last):
  File "/tools/software/anaconda3/envs/py3.7-tzuyun/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/tools/software/anaconda3/envs/py3.7-tzuyun/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tools/software/anaconda3/envs/py3.7-tzuyun/lib/python3.6/site-packages/keras2ncnn/__main__.py", line 12, in <module>
    sys.exit(_main())
  File "/tools/software/anaconda3/envs/py3.7-tzuyun/lib/python3.6/site-packages/keras2ncnn/keras2ncnn.py", line 130, in main
    graph_seq)
  File "/tools/software/anaconda3/envs/py3.7-tzuyun/lib/python3.6/site-packages/keras2ncnn/keras_debugger.py", line 214, in emit_file
    'w+').write(c_payload)
FileNotFoundError: [Errno 2] No such file or directory: '.keras2ncnn_build/ncnn/benchmark/keras2ncnn.cpp'

Keras Faster R-CNN to NCNN

Faster R-CNN与c其他网络不同的是有两个输出,cls_prob概率向量和位置偏移量bbox_pred。如何利用这个工具转化。

print unsupported,Please

Can you print the unsupported ones?
(能否将不支持的打印出来?)

Reading and parsing keras h5df file...
Start graph optimizing pass...
        Removing unused nodes...
        Removing squeeze reshape after pooling...
        Refreshing graph...
Converting keras graph to ncnn graph...
[ERROR] Operator Sequential not support.
=========================================
{'name': 'sequential', 'layers': [{'class_name': 'InputLayer', 'config': {'batch_input_shape': [None, 180, 180, 3], 'dtype': 'float32', 'sparse': False, 'ragged': False, 'name': 'random_flip_input'}}, {'class_name': 'RandomFlip', 'config': {'name': 'random_flip', 'trainable': True, 'batch_input_shape': [None, 180, 180, 3], 'dtype': 'float32', 'mode': 'horizontal', 'seed': None}}, {'class_name': 'RandomRotation', 'config': {'name': 'random_rotation', 'trainable': True, 'dtype': 'float32', 'factor': 0.1, 'fill_mode': 'reflect', 'fill_value': 0.0, 'interpolation': 'bilinear', 'seed': None}}, {'class_name': 'RandomZoom', 'config': {'name': 'random_zoom', 'trainable': True, 'dtype': 'float32', 'height_factor': 0.1, 'width_factor': None, 'fill_mode': 'reflect', 'fill_value': 0.0, 'interpolation': 'bilinear', 'seed': None}}]}
=========================================
Failed to convert at /opt/homebrew/lib/python3.9/site-packages/keras2ncnn/keras_converter.py:1433 parse_keras_graph()

self.model_config['config'] is a list in model

I want to convert this model to ncnn but failed. I found that the self.model_config['config'] in this model is a list, which caused error.

Traceback (most recent call last):
  File "/home/tommy/miniconda3/envs/pytorch/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/home/tommy/miniconda3/envs/pytorch/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/tommy/miniconda3/envs/pytorch/lib/python3.8/site-packages/keras2ncnn/__main__.py", line 12, in <module>
    sys.exit(_main())
  File "/home/tommy/miniconda3/envs/pytorch/lib/python3.8/site-packages/keras2ncnn/keras2ncnn.py", line 55, in main
    H5dfParser(args.input_file).parse_graph(keras_graph)
  File "/home/tommy/miniconda3/envs/pytorch/lib/python3.8/site-packages/keras2ncnn/h5df_parser.py", line 111, in parse_graph
    for layers in self.model_config['config']['layers']:
TypeError: list indices must be integers or slices, not str

[ERROR] Failed to load structure descriptor from h5df file.

https://github.com/idealo/image-quality-assessment

python -m keras2ncnn -i weights_mobilenet_aesthetic_0.07.hdf5 -o ./

get this error
Reading and parsing keras h5df file...
[ERROR] Failed to load structure descriptor from h5df file.
You may load a weight only file.
Such issue may caused by following ways:
1. You are using model.save_weights instead of model.save
2. You are trying to load a weight file download from somewhere.
If you are very confident of your file, please report a bug at:

Another issue in conversion

Hello
How are you?
Thanks to your continuous updating.
I met an another issue when converting a Keras model with the latest converter.

image

This keras model works well on Keras 2.3.1 and Tensorflow 1.14.0.
I send the model.
https://we.tl/t-yaiIGvSxNs
Please fix this issue asap.
Thanks.

Not same result

Hi
Thanks for your continuous updating.
I converted the Keras model with the latest version of your project and compared the result from the NCNN model with one from the original model.
But the results are too different from each other.

The results from the Keras model are the following:
the real face score: 0.31723082
the fake face score: 0.1382943

The results from the NCNN model are the following:
the real face score: 0.68066406
the fake face score: 0.7392578

I send the original Keras model, the converted NCNN model, and the inference scripts.
https://we.tl/t-vJESHtg4QF
Could u check on your side again?
Thanks

Mobilenetv3 Keras error

Hi, I try to convert model to nccn using Mobilenetv3Small, but I get this error

ERROR] Operator Rescaling not support.

{'name': 'rescaling', 'trainable': False, 'dtype': 'float32', 'scale': 0.00784313725490196, 'offset': -1.0}

Mi training code:

IMG_SIZE = 320 # All images will be resized to 160x160

def format_example(pair):
  image, label = pair['image'], pair['label']
  image = tf.cast(image, tf.float32)
  image = (image/127.5) - 1
  image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
  return image, label
IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)

# Create the base model from the pre-trained model MobileNet V2
base_model = tf.keras.applications.MobileNetV3Small(input_shape=IMG_SHAPE,
                                               include_top=False,
                                               weights='imagenet')

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
feature_batch_average = global_average_layer(feature_batch)

prediction_layer = tf.keras.layers.Dense(1)
prediction_batch = prediction_layer(feature_batch_average)

model = tf.keras.Sequential([
  base_model,
  global_average_layer,
  prediction_layer
])

base_learning_rate = 0.0001
model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=base_learning_rate),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

Model summary

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 MobilenetV3small (Functiona  (None, 13, 13, 576)      939120    
 l)                                                              
                                                                 
 global_average_pooling2d (G  (None, 576)              0         
 lobalAveragePooling2D)                                          
                                                                 
 dense (Dense)               (None, 1)                 577       
                                                                 
=================================================================
Total params: 939,697
Trainable params: 577
Non-trainable params: 939,120
_________________________________________________________________

model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer = tf.keras.optimizers.RMSprop(learning_rate=base_learning_rate/10),
              metrics=['accuracy'])

Another question, what is the correct mean - norm values for this model?

Thanks

raise NotImplementedError

{'layer': {'class_name': 'ReLU', 'config': {'name': 're_lu', 'trainable': True, 'dtype': 'float32', 'max_value': None, 'negative_slope': 0.0, 'threshold': 0.0}, 'name': 're_lu', 'inbound_nodes': [[['batch_normalization', 0, 0, {}]]]}, 'weight': None}

'max_value': None

为啥 relu 会有这个参数 ,是我的问题吗?

请问大佬,我该怎么规避这个问题呢

Not same as the original model result

Hello
How are you?
Thanks for your continuous updating.
I converted a keras model for predicting a liveness score of face, which is a binary classification model in general.
But the result from the ncnn model is NOT same as the original keras model.
In other words, the result from the ncnn model is always 1.0 for both real and fake face images.
I send the original keras model, the inference script and sample images.
https://we.tl/t-A0orRSIWn8
Please check and fix the issue asap.
Thanks.

请韩佬有空帮我瞅瞅这两个OP,SeparableConv2D 和 BilinearUpsampling

环境:tf2.1,keras2.3
from tensorflow.keras.models import load_model
model = load_model("./SOD.h5", custom_objects={'BilinearUpsampling': BilinearUpsampling}, compile=False)
运行预测没有问题。

使用你的仓库,在转换过程中遇到问题:
[ERROR] Operator SeparableConv2D not support.
使用另外一个老哥的仓库(https://github.com/azeme1/keras2ncnn)遇到问题:
ValueError: Unknown layer: BilinearUpsampling

附上模型文件
SOD.zip

Decreased accuracy of results

when i convert h5 model to ncnn model
process with the training data, the ncnn model result is worse than h5 result
I check the input data and find nothing different

i want to checkout if it is a problem with model conversion

but there is error with debug mode

image

please help~

Thankyou very much

请韩佬有空帮我瞅瞅这两个OP,SeparableConv2D 和 BilinearUpsampling

环境:tf2.1,keras2.3
from tensorflow.keras.models import load_model
model = load_model("./SOD.h5", custom_objects={'BilinearUpsampling': BilinearUpsampling}, compile=False)
运行预测没有问题。

使用你的仓库,在转换过程中遇到问题:
[ERROR] Operator SeparableConv2D not support.
使用另外一个老哥的仓库(https://github.com/azeme1/keras2ncnn)遇到问题:
ValueError: Unknown layer: BilinearUpsampling

附上模型文件
SOD.zip

mobilenet.h5转换KeyError: 'threshold'错误

H5文件:

https://github.com/lutzroeder/netron/ 的 Keras: mobilenet 

命令:

python3 -m keras2ncnn -i ~/Downloads/mobilenet.h5  -o ./

出错信息

 File "/home/hx/.local/lib/python3.6/site-packages/keras2ncnn/keras2ncnn.py", line 67, in main
    KerasConverter().parse_keras_graph(keras_graph, ncnn_graph, NcnnParamDispatcher())
  File "/home/hx/.local/lib/python3.6/site-packages/keras2ncnn/keras_converter.py", line 850, in parse_keras_graph
    ncnn_helper)
  File "/home/hx/.local/lib/python3.6/site-packages/keras2ncnn/keras_converter.py", line 422, in ReLU_helper
    if layer['layer']['config']['threshold'] != 0:
KeyError: 'threshold'

do not support Prelu

when i convert the enet model to ncnn , the prelu operator is not support

can you help to support the operator in the new version?

Thankyou Verymuch

Uploading 1.PNG…

fizyr/keras-retinanet2ncnn

got KeyError: 'attr'
class UpsampleLike(keras.layers.Layer):
""" Keras layer for upsampling a Tensor to be the same shape as another Tensor.
"""

def call(self, inputs, **kwargs):
    source, target = inputs
    target_shape = keras.backend.shape(target)
    if keras.backend.image_data_format() == 'channels_first':
        source = backend.transpose(source, (0, 2, 3, 1))
        output = backend.resize_images(source, (target_shape[2], target_shape[3]), method='nearest')
        output = backend.transpose(output, (0, 3, 1, 2))
        return output
    else:
        return backend.resize_images(source, (target_shape[1], target_shape[2]), method='nearest')

this OP UpsampleLike is not support, Can you help me solve it,thanks!

VGG16-SSD error

[Reading](url

) and parsing keras h5df file...
Start graph optimizing pass...
Removing unused nodes...
Removing squeeze reshape after pooling...
Refreshing graph...
Converting keras graph to ncnn graph...
[ERROR] Operator L2Normalization not support.

{'name': 'conv4_3_norm', 'trainable': True, 'gamma_init': 20}

model h5 file https://we.tl/t-7NHgYv7rwW

Input layer didn't get converted

Trying to convert keras model to NCNN.

When tried to convert model, it got converted successfully but convolution layer was the first layer

Convolution              conv2d_3                                0 1  conv2d_3_blob 0=16 1=3 2=1 3=1 4=0 5=1 6=432 9=1 11=3 12=1 13=1 

Not able to understand why input layer (data) couldn't get converted. Any reasons ?

Please help ! thank you.

@MarsTechHAN

[ERROR] Failed to read h5df file. You are not selecting a valid keras model file.

test.zip
hello,There's a problem where i executive command of "python -m keras2ncnn -i test.h5 -i ./"
the error is as follows:
"
Reading and parsing keras h5df file...
[ERROR] Failed to read h5df file.
You are not selecting a valid keras model file.
You can check it by either opening it by Keras or Netron.
If you are very confident of your file, please repoert a bug at: https://github.com/MarsTechHAN/keras2ncnn
"

Lambda support

I was wondering if tf.keras.layers.Lambda can be supported. My model looks like:

Imports & utility:

from tensorflow.keras.activations import softmax
from tensorflow.keras.models import Model
from tensorflow.keras.layers import (
    Activation, Concatenate, Dense, Dropout, GlobalAveragePooling2D,
    Input, MaxPool2D, Lambda, Reshape
)

# block_no_activation is the same w/o Activation
def block_bn(i, k=3, n_c=64, s=1, padding='same'):
    x1 = Conv2D(kernel_size=k, filters=n_c, strides=s, padding=padding,
                kernel_regularizer=regularizers.l2(0.01), use_bias=False)(i)
    x2 = BatchNormalization()(x1)
    x2 = Activation(relu)(x2)
    return x2, x1

Model:

def model():
    h, w = 70, 140
    input_tensor = Input((h, w, 1))
    x, _ = block_bn(input_tensor)
    # ... More Conv2D -> BatchNorm -> Activation ...
    x, _ = block_bn(x, k=1, n_c=1024, s=1, padding='same')
    x = block_no_activation(x, k=1, n_c=259, s=1, padding='same')
    x = GlobalAveragePooling2D()(x)
    x = Reshape((7, 37, 1))(x)
    x = Lambda(lambda x: softmax(x, axis=-2))(x)
    return Model(inputs=input_tensor, outputs=x)

Conversion Issue

Hello
How are you?
Thanks for contributing this project.
I have a Keras model.
I am going to convert this model to NCNN.
I tried to do this with your script.

But I met the following issue.

Reading and parsing keras h5df file...
Traceback (most recent call last):
File "keras2ncnn.py", line 1625, in
H5dfParser(args.input_file).parse_graph(keras_graph)
File "keras2ncnn.py", line 99, in parse_graph
self.parse_sequential_graph(graph_helper)
File "keras2ncnn.py", line 110, in parse_sequential_graph
layers['config']['layers'], graph_helper)
File "keras2ncnn.py", line 131, in parse_model_graph
layer['name'])})
File "keras2ncnn.py", line 72, in find_weights_root
layer = layer[layer_name]
File "h5py_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "C:\Users\admin\Anaconda3\envs\py37_tf1.x\lib\site-packages\h5py_hl\group.py", line 262, in getitem
oid = h5o.open(self.id, self._e(name), lapl=self._lapl)
File "h5py_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5o.pyx", line 190, in h5py.h5o.open
KeyError: "Unable to open object (object 'input_1' doesn't exist)"

u can get the keras model from here: https://we.tl/t-ZdD7JQK1Xf
environment:
Keras: 2.3.1
Tensorflow: 1.14.0
h5py: 2.9.0

model conversion error

error is failed to convert at C:\Program Files\Python36\lib\site-packages\keras2ncnn\keras_converter.py:1433 parse_keras_graph()

also this error was at the beginning [ERROR] Operator Sequential not support.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.