python中的模型训练和Golang中的运行模型,模型导入过程中的问题
时间:2024-03-17
浏览:188
作者:佚名
在使用 TensorFlow 2.3 训练模型并使用 TensorFlow 1.15.0 在 Go 中运行模型时,遇到导入过程中的问题。使用 TensorFlow 2.3 的 Python 代码无法加载 TensorFlow 1.15.0 中保存的模型,导致 Go 中出现异常。本文将分析导致该问题的根本原因,并提供解决方案,以解决导入模型时的困难。
我安装了最新版本的 tensorflow (2.3),在 python 下运行良好,但在 golang 下出现异常:
...但不包含包 github.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto
我将版本更改为 1.15.0,让 tensorflow 能够与 golang 配合使用
现在,我面临以下问题:
使用 tensorflow 2.3 的 python 代码
import tensorflow as tf
df = pd.read_csv(data_path, sep=';')
x = df[df.columns[:8]]
y = df[df.columns[8:-1]]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3)
model = tf.keras.sequential()
model.add(tf.keras.layers.dense(8, activation='relu', name="inputnode"))
model.add(tf.keras.layers.dense(150, activation='relu'))
model.add(tf.keras.layers.dense(3, name="infernode"))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=500)
tf.keras.models.save_model(model=model, filepath='./', save_format='tf')
使用 tensorflow 1.15.0 的 golang 代码
model, err := tf.loadsavedmodel("./", []string{"serve"}, nil)
if err != nil {
fmt.printf("error loading saved model: %s\n", err.error())
return
}
defer model.session.close()
data := [][]float32{make([]float32, 8)}
data[0][0] = 1.0
data[0][1] = 1.0
data[0][2] = 1.0
data[0][3] = 1.0
data[0][4] = 1.0
data[0][5] = 1.0
data[0][6] = 1.0
data[0][7] = 1.0
tensor, _ := tf.newtensor(data)
result, err := model.session.run(
map[tf.output]*tf.tensor{
model.graph.operation("inputnode_input").output(0): tensor, // replace this with your input layer name
},
[]tf.output{
model.graph.operation("infernode").output(0), // replace this with your output layer name
},
nil,
)
if err != nil {
fmt.printf("error running the session with input, err: %s\n", err.error())
return
}
fmt.printf("result value: %v \n", result[0].value())
golang 抛出此异常:
-- fail: testmlpredict (6.93s)
panic: nil-operation. if the output was created with a scope object, see scope.err() for details. [recovered]
panic: nil-operation. if the output was created with a scope object, see scope.err() for details.
这里是一个示例特征向量
header: 20 15 10 5 0 branch1 branch2 branch3 output1 output2 output3 data: 2.518878 3.778791 5.021497 5.559673 5.402780 0.0 0.109421 0.109253 0.0 0.0 1.0
我做错了什么?输入和输出名称应该正确。
解决方案
我实际上修复了我维护的 tensorflow 分支中的第一个问题,其中包含所有已编译的 protobuf。该 fork 是软件包 galeone/tfgo 的依赖项,它会使用 go mod 自动下载。
你试试
go get github.com/galeone/tfgo
您将能够使用tensorflow/go和tensorflow/op包以及tfgo的所有附加功能。
理论要掌握,实操不能落!以上关于《python中的模型训练和Golang中的运行模型,模型导入过程中的问题》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
