【发布时间】:2019-02-22 20:01:24
【问题描述】:
我正在尝试使用 Django 提供通用句子编码器。
代码一开始被初始化为后台进程(通过使用supervisor等程序),然后它使用TCP套接字与Django通信,最终返回编码语句。
import socket
from threading import Thread
import tensorflow as tf
import tensorflow_hub as hub
import atexit
# Pre-loading the variables:
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2")
session = tf.Session()
session.run(tf.global_variables_initializer())
session.run(tf.tables_initializer())
atexit.register(session.close) # session closes if the script is halted
...
# Converts string to vector embedding:
def initiate_connection(conn):
data = conn.recv(1024)
conn.send(session.run(embed([data])))
conn.close()
# Process in background, waiting for TCP message from views.py
while True:
conn, addr = _socket.accept()
_thread = Thread(target=initiate_connection, args=(conn,)) # new thread for each request (could be limited to n threads later)
_thread.demon = True
_thread.start()
conn.close()
但我在执行conn.send(session.run(embed([data])))时收到以下错误:
RuntimeError: 模块必须在它被实例化的图中应用 为。
我基本上是尝试在 tensorflow 中预加载表(因为这需要相当多的时间),但 tensorflow 不允许我使用预定义的会话。
我该如何解决这个问题?有没有办法预加载这些变量?
附言 我相信this Github issue page 可能会解决我的问题,但我不确定如何实施。
【问题讨论】:
标签: python django tensorflow tensorflow-hub