如何将神经网络模型转换为独立函数的源代码



我必须在无法访问第三方库的环境中运行源代码,并且我希望能够在该环境中使用神经网络模型进行预测。我不能运行编译后的代码,它必须是源代码。

我想训练我的神经网络使用流行的库,如Keras, Pytorch, Tensorflow等…并将该模型转换为可以在无法访问该库的环境中运行的源代码函数。因此,生成的代码不能是对库调用的包装。它需要拥有内部所需的一切以便能够在没有外部依赖的情况下运行神经网络。而且必须是源代码,而不是编译后的代码。

在研究这个问题时,我意识到大多数库都有api来将模型保存为不同类型的序列化格式,但没有办法生成可以自己运行的代码。

我该怎么做呢?

为了非常清楚,这里有一个我想从神经网络模型生成的代码示例:

function predict(input) {
// Here is all the code that contains the topology and weights of the network 
// along with the code needed to load it up into memory and exercise the network, 
// using no external libraries.
return output;
}

所以我在寻找的是一个库,或者一种技术,可以让我做:

var neuralNetworkSourceCode = myNeuralNetworkModel.toSourceCode();
// neuralNetworkSourceCode is a string containing the source code described in the previous example

它可以将源代码保存到一个文件中,而不仅仅是生成一个字符串,对我来说没有什么不同。在这一点上,我也不关心它生成源代码的语言,但理想情况下,它将是其中之一:c, c++, c#, java, python, javascript, go或rust。

有这样的库吗?如果没有,我应该如何实现这个功能。

之前有人问过类似的问题:将Keras模型转换为c++或将Keras模型转换为C,这些线程有一些可能仍然相关的建议。也没有提到keras2c(论文,代码),它在设置库后提供了k2c(model, ...)函数。


在简单MNIST convnet示例中创建的模型上调用k2c,像这样生成一个.csv文件,其中包含权重和一些用于设置预测的代码:

import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from keras2c import k2c
(x_train, y_train), (_, _) = keras.datasets.mnist.load_data()
x_train = np.expand_dims(x_train.astype("float32") / 255, -1)
y_train = keras.utils.to_categorical(y_train, 10)
model = keras.Sequential([
keras.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")])
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=128, epochs=15, validation_split=0.1)
k2c(model, "MNIST", malloc=True, num_tests=10, verbose=True)

make编译include/的内容,然后:

gcc -std=c99 -I./include/ -o predict_mnist MNIST.c MNIST_test_suite.c -L./include/ -l:libkeras2c.a -lm

运行可执行文件显示了一个快速基准测试:

$ ./predict_mnist
Average time over 10 tests: 6.059000e-04 s
Max absolute error for 10 tests: 3.576279e-07

最新更新