在tf.contrib.learn tensorflow中创建估算器。期望的字符串或字节类对象错误

时间:2017-03-08 01:34:52

标签: python tensorflow

我正在尝试在tensorflow中创建自己的Estimator函数,而不是使用DNNRegression函数来无法更改超参数。我正在关注这个tensorflow.org教程:

https://www.tensorflow.org/extend/estimators

我也从tensorflow.org页面获得了数据。这是我的代码,带有相应的错误。

非常感谢你的帮助!

`from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import pandas as pd
import tensorflow as tf
import numpy as np
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib`

COLUMNS = ["crim", "zn", "indus", "nox", "rm", "age",
           "dis", "tax", "ptratio", "medv"]

FEATURES = ["crim", "zn", "indus", "nox", "rm",
            "age", "dis", "tax", "ptratio"]

LABEL = "medv"

training_set = pd.read_csv("boston_train.csv",skipinitialspace=True,skiprows=1,names=COLUMNS)

test_set =pd.read_csv("boston_test.csv",skipinitialspace=True,skiprows=1,names=COLUMNS)

prediction_set = pd.read_csv("boston_predict.csv",skipinitialspace=True,skiprows=1,names=COLUMNS)

x_training_set = training_set.ix[:,0:9]
x_training_set2 = x_training_set.values
y_training_set = training_set.ix[:,9]
y_training_set2 = y_training_set.values

# Set model params
model_params = {"learning_rate": LEARNING_RATE}

# Instantiate Estimator
nn = tf.contrib.learn.Estimator(model_fn=model_fn, params=model_params)

def model_fn(features, targets, mode, params):

    h_1 = tf.nn.relu(features,10)
    h_2 = tf.nn.relu(h_1, 10)
    output_layer =  tf.contrib.layers.fully_connected((h_2, 1), activation_fn=None)

    predictions_dict = {"pred": output_layer}


    # Calculate loss using mean squared error
    loss = tf.metrics.root_mean_squared_error(tf.cast(targets, tf.float32), predictions)

    # Calculate root mean squared error as additional eval metric
    eval_metric_ops = {"rmse":tf.metrics.root_mean_squared_error(tf.cast(targets, tf.float32), predictions)}

    train_op = tf.contrib.layers.optimize_loss(loss=loss, global_step=tf.contrib.framework.get_global_step(),learning_rate=params["learning_rate"],optimizer="SGD")

    return model_fn_lib.ModelFnOps(mode=mode,predictions=predictions_dict,loss=loss,train_op=train_op,eval_metric_ops=eval_metric_ops)

nn.fit(x=x_training_set2, y=y_training_set2,input_fn=None, steps=200)

当我运行最后一行时出现错误,如下所示:

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py:247: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
  equality = a == b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-91-8d36dcccfcd6> in <module>()
----> 1 nn.fit(x=x_training_set2, y=y_training_set2,input_fn=None, steps=200)

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py in new_func(*args, **kwargs)
    278             _call_location(), decorator_utils.get_qualified_name(func),
    279             func.__module__, arg_name, date, instructions)
--> 280       return func(*args, **kwargs)
    281     new_func.__doc__ = _add_deprecated_arg_notice_to_docstring(
    282         func.__doc__, date, instructions)

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
    408     _verify_input_args(x, y, input_fn, None, batch_size)
    409     if x is not None:
--> 410       SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors)
    411       return self
    412 

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in fit(self, x, y, batch_size, steps, max_steps, monitors)
   1351                         steps=steps,
   1352                         max_steps=max_steps,
-> 1353                         monitors=all_monitors)
   1354     return self
   1355 

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py in new_func(*args, **kwargs)
    278             _call_location(), decorator_utils.get_qualified_name(func),
    279             func.__module__, arg_name, date, instructions)
--> 280       return func(*args, **kwargs)
    281     new_func.__doc__ = _add_deprecated_arg_notice_to_docstring(
    282         func.__doc__, date, instructions)

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in fit(self, x, y, input_fn, steps, batch_size, monitors, max_steps)
    424       hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps))
    425 
--> 426     loss = self._train_model(input_fn=input_fn, hooks=hooks)
    427     logging.info('Loss for final step: %s.', loss)
    428     return self

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in _train_model(self, input_fn, hooks)
    932       features, labels = input_fn()
    933       self._check_inputs(features, labels)
--> 934       model_fn_ops = self._call_legacy_get_train_ops(features, labels)
    935       ops.add_to_collection(ops.GraphKeys.LOSSES, model_fn_ops.loss)
    936       all_hooks.extend([

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in _call_legacy_get_train_ops(self, features, labels)
   1001 
   1002   def _call_legacy_get_train_ops(self, features, labels):
-> 1003     train_ops = self._get_train_ops(features, labels)
   1004     if isinstance(train_ops, model_fn_lib.ModelFnOps):  # Default signature
   1005       return train_ops

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in _get_train_ops(self, features, labels)
   1160       `ModelFnOps` object.
   1161     """
-> 1162     return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
   1163 
   1164   def _get_eval_ops(self, features, labels, metrics):

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py in _call_model_fn(self, features, labels, mode)
   1131     if 'model_dir' in model_fn_args:
   1132       kwargs['model_dir'] = self.model_dir
-> 1133     model_fn_results = self._model_fn(features, labels, **kwargs)
   1134 
   1135     if isinstance(model_fn_results, model_fn_lib.ModelFnOps):

<ipython-input-74-fb3e83994074> in model_fn(features, targets, mode, params)
      1 def model_fn(features, targets, mode, params):
      2 
----> 3     h_1 = tf.nn.relu(features,10)
      4     h_2 = tf.nn.relu(h_1, 10)
      5     output_layer =  tf.contrib.layers.fully_connected((h_2, 1), activation_fn=None)

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_nn_ops.py in relu(features, name)
   2148     A `Tensor`. Has the same type as `features`.
   2149   """
-> 2150   result = _op_def_lib.apply_op("Relu", features=features, name=name)
   2151   return result
   2152 

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    373     inputs = []
    374     input_types = []
--> 375     with g.as_default(), ops.name_scope(name) as scope:
    376 
    377       # Perform input type inference

C:\Users\pinouche\Anaconda3\lib\contextlib.py in __enter__(self)
     57     def __enter__(self):
     58         try:
---> 59             return next(self.gen)
     60         except StopIteration:
     61             raise RuntimeError("generator didn't yield") from None

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in name_scope(name, default_name, values)
   4218     values = []
   4219   g = _get_graph_from_inputs(values)
-> 4220   with g.as_default(), g.name_scope(n) as scope:
   4221     yield scope
   4222 # pylint: enable=g-doc-return-or-yield

C:\Users\pinouche\Anaconda3\lib\contextlib.py in __enter__(self)
     57     def __enter__(self):
     58         try:
---> 59             return next(self.gen)
     60         except StopIteration:
     61             raise RuntimeError("generator didn't yield") from None

C:\Users\pinouche\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in name_scope(self, name)
   2905         # Scopes created in the root must match the more restrictive
   2906         # op name regex, which constrains the initial character.
-> 2907         if not _VALID_OP_NAME_REGEX.match(name):
   2908           raise ValueError("'%s' is not a valid scope name" % name)
   2909     try:

TypeError: expected string or bytes-like object

0 个答案:

没有答案