在生产环境中对模型运行预测时出现内存泄漏。这是代码:
import tensorflow as tf
from tensorflow.python.keras import layers, losses
class Model:
@staticmethod
@tf.keras.utils.register_keras_serializable()
def data_standardization(input_data): # "CH3-CH=CH-CH(NO2)Br"
input_data = tf.strings.lower(input_data) # "ch3-ch=ch-ch(no2)br"
return tf.strings.regex_replace(input_data, r".", r"\0 ") # "c h 3 - c h = c h - c h ( n o 2 ) b r"
def __init__(self, model_path=None, max_features=None, embedding_dim=None):
if model_path is not None:
self.model = tf.keras.models.load_model(model_path)
elif max_features is not None and embedding_dim is not None:
self.model = tf.keras.Sequential([
layers.Embedding(max_features + 1, embedding_dim),
layers.Dropout(0.2),
layers.Dense(256, activation="relu"),
layers.GlobalAveragePooling1D(),
layers.Dropout(0.2),
layers.Dense(1),
])
self.model.compile(
optimizer="adam",
metrics=tf.metrics.BinaryAccuracy(threshold=0.0),
loss=losses.BinaryCrossentropy(from_logits=True),
)
def predict(self, text):
return self.model.predict([text], verbose=0)[0][0]
我读到
.predict
对于生产来说并不理想。我尝试使用 self.model("test")
代替,但得到了这个:
TypeError: Inputs to a layer should be tensors. Got 'test' (of type <class 'str'>) as input for layer 'sequential_7'.
而且我不确定在这种情况下获取张量的正确方法。
那么,我应该做哪些改变来防止内存泄漏?
出现错误的原因是您在引号中指定了变量。您需要将其作为变量传递:
result = model(test, training=False)
其中 test 应该是张量。
记住 model.predict() 返回一个 numpy 数组,而 model() 返回一个张量。您应该首先预处理您的数据。