是否可以训练tensorflow模型,然后将其导出为无需tensorflow即可访问的内容?我想将一些机器学习应用到一个学校项目中,其中的代码是在一个在线门户上提交的-它没有安装tensorflow,只安装了标准库。我可以上传额外的文件,但任何tensorflow文件都需要tensorflow才能理解...我必须从头开始编写ML代码吗?
发布于 2019-05-23 07:43:23
如果你只使用简单的全连接层,你可以在numpy中实现它们,不会有大的问题。将内核和偏置保存到文件中(或者将权重作为python常量注入到代码中),并对每一层执行以下操作:
# preallocate w once at the beginning for each layer
w = np.empty([len(x), layer['kernel'].shape[1]])
# x is input, mult kernel with x, write result to w
x.dot(layer['kernel'], out=w) # matrix mult with kernel
w += layer['bias'] # add bias
out = np.maximum(w, 0) # ReLU或者您可以尝试这个库(对于旧的tensorflow版本):https://github.com/riga/tfdeploy。它完全是用numpy编写的,你可以试着从其中剪掉一些代码片段。
发布于 2019-05-22 23:34:13
除非你把tensorflow和它的所有文件带到你的应用程序中。除此之外,不能导入tensorflow,也不能拥有任何依赖于tensorflow的模块或代码。
发布于 2019-05-23 03:04:14
是的,这是可能的。假设你正在使用非常简单的网络,比如2层或3层完全连接的神经网络,你可以将.pb文件中的权重和偏差项保存/提取为任何格式(例如.csv),并相应地使用它们。
例如,
import tensorflow as tf
import numpy as np
from tensorflow.python.platform import gfile
from tensorflow.python.framework import tensor_util
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
config = tf.ConfigProto(allow_soft_placement=True,
log_device_placement=True,
gpu_options=gpu_options)
GRAPH_PB_PATH = "./YOUR.pb"
with tf.Session(config=config) as sess:
print("load graph")
with gfile.FastGFile(GRAPH_PB_PATH, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
graph_nodes = [n for n in graph_def.node]
wts = [n for n in graph_nodes if n.op == 'Const']
result = []
result_name = []
for n in wts:
result_name.append(n.name)
result.append(tensor_util.MakeNdarray(n.attr['value'].tensor))
np.savetxt("layer1_weight.csv", result[0], delimiter=",")
np.savetxt("layer1_bias.csv", result[1], delimiter=",")
np.savetxt("layer2_weight.csv", result[2], delimiter=",")
np.savetxt("layer2_bias.csv", result[3], delimiter=",")https://stackoverflow.com/questions/56260192
复制相似问题