不引入tens的负荷张量流模型

2024-04-26 11:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能训练一个tensorflow模型,然后将其导出为没有tensorflow就可以访问的东西?我想将一些机器学习应用到一个学校项目中,在这个项目中,代码是在一个在线门户上提交的——它没有安装tensorflow,只有标准库。我可以上传额外的文件,但任何tensorflow文件都需要tensorflow来理解。。。我必须从头开始写我的ML代码吗?你知道吗


Tags: 文件项目代码模型机器标准门户tensorflow
3条回答

如果您只使用简单的完全连接层,那么就可以在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

或者您可以尝试这个lib(对于旧的tensorflow版本):https://github.com/riga/tfdeploy。它完全只使用numpy编写,您可以尝试从中剪切一些代码片段。你知道吗

是的,这是可能的。假设您正在使用非常简单的网络,例如2或3层完全连接的NN,您可以将.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=",")

差不多,除非你把tensorflow和它的所有文件都带到你的应用程序里。除此之外,不,您不能导入tensorflow或拥有任何依赖tensorflow的模块或代码。你知道吗

相关问题 更多 >