我必须在无法访问第三方库的环境中运行源代码,并且我希望能够在该环境中使用神经网络模型进行预测。我无法运行编译后的代码,它必须是源代码。
我想使用 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。
有没有一个库可以做到这一点?如果没有,我应该如何实现这个功能。
最佳答案
不久前有人问过类似的问题:Convert Keras model to C++或Convert Keras model to C ,并且这些线程有一些可能仍然相关的建议。都没有提到 keras2c
( paper 、 code ),它在设置库后提供了 k2c(model, ...)
函数。
在从 Simple 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
关于machine-learning - 如何将神经网络模型转换为独立函数源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74855405/