我正在使用 TensorFlow (1.1) 高级 API Estimators创建我的神经网络。但是我将它用到一个类中,我必须调用我的类的一个实例来生成神经网络模型。 (这里是self.a)
class NeuralNetwork(object):
def __init__(self):
""" Create neural net """
regressor = tf.estimator.Estimator(model_fn=self.my_model_fn,
model_dir="/tmp/data")
// ...
def my_model_fn(self, features, labels, mode):
""" Generate neural net model """
self.a = a
predictions = ...
loss = ...
train_op = ...
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op)
但是我得到了错误: ValueError:model_fn [...] 具有以下非预期参数:['self']。 我试图为我的模型的参数删除 self 但得到另一个错误 TypeError: … got multiple values for keyword argument . 有什么方法可以将这些 EstimatorSpec 用于类中吗?
请您参考如下方法:
看起来 Estimator 的参数检查有点过分了。作为解决方法,您可以将成员函数 model_fn 包装在 lambda 中,如下所示:
import tensorflow as tf
class ModelClass(object):
def __init__(self):
self._constant = 2.
self.regressor = tf.estimator.Estimator(
model_fn=lambda features, labels, mode: self._model_fn(
features, labels, mode))
def _model_fn(self, features, labels, mode):
loss = tf.constant(self._constant)
train_op = tf.no_op()
return tf.estimator.EstimatorSpec(
mode=mode,
loss=loss,
train_op=train_op)
ModelClass()
但是,这很烦人。你介意吗filing a feature request on Github放宽此参数检查成员函数?
更新:应该在 TensorFlow 1.3+ 中修复。谢谢袁!
