# 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
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=",")
如果您只使用简单的完全连接层,那么就可以在numpy中实现它们,而不会出现大问题。将内核和偏差保存到文件中(或将权重作为python常量直接注入到代码中),并对每个层执行以下操作:
或者您可以尝试这个lib(对于旧的tensorflow版本):https://github.com/riga/tfdeploy。它完全只使用numpy编写,您可以尝试从中剪切一些代码片段。你知道吗
是的,这是可能的。假设您正在使用非常简单的网络,例如2或3层完全连接的NN,您可以将.pb文件中的权重和偏差项保存/提取为任何格式(例如.csv),并相应地使用它们。你知道吗
例如
差不多,除非你把tensorflow和它的所有文件都带到你的应用程序里。除此之外,不,您不能导入tensorflow或拥有任何依赖tensorflow的模块或代码。你知道吗
相关问题 更多 >
编程相关推荐