Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Konver Keras-Model to RKNN #201

Open
ugoebel opened this issue Oct 11, 2024 · 0 comments
Open

Konver Keras-Model to RKNN #201

ugoebel opened this issue Oct 11, 2024 · 0 comments

Comments

@ugoebel
Copy link

ugoebel commented Oct 11, 2024

Hello,
I have been trying to convert a Tensorflow/Keras model into an RKNN model for some time now. I have the model here:



import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf
import onnx
import tf2onnx


# 1. MNIST-Modell mit CNN in Keras

# Daten laden und vorbereiten
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255

# Modell definieren
model = keras.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
    layers.MaxPooling2D(pool_size=(2, 2)),
    layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
    layers.MaxPooling2D(pool_size=(2, 2)),
    layers.Flatten(),
    layers.Dropout(0.5),
    layers.Dense(10, activation="softmax")
])

# Modell kompilieren
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

# Modell trainieren
model.fit(x_train, y_train, batch_size=128, epochs=5, validation_split=0.1)

# Modell evaluieren
score = model.evaluate(x_test, y_test, verbose=0)
print(f"Test loss: {score[0]}")
print(f"Test accuracy: {score[1]}")

# 2. Speichern des Modells als ONNX

# Modell als SavedModel speichern
tf.saved_model.save(model, "mnist_model")

# Konvertierung zu ONNX
input_signature = [tf.TensorSpec([None, 28, 28, 1], tf.float32, name='input')]
#onnx_model, _ = tf2onnx.convert.from_keras(model)
onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=13)
onnx.save(onnx_model, "mnist_model.onnx")

I have not been able to do this so far. Could someone please give me an example of how to do this. I have seen many examples using PyTorch. But I am more familiar with Tensorflow and would like to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant