使用tf.contrib.learn来解决基本的逻辑分类器

时间:2017-07-23 12:45:54

标签: python tensorflow logistic-regression

我正在了解Tensorflow中的tf.contrib.learn,并且正在使用自制练习。练习是按如下方式对三个区域进行分类,其中x1和x2为输入,标签为三角形/圆形/十字形: enter image description here

我的代码能够适合数据并对其进行评估。但是,我似乎无法预测工作。代码如下。有什么想法吗?

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile

from six.moves import urllib

import pandas as pd
import tensorflow as tf
import numpy as np

FLAGS = None

myImportedDatax1_np = np.array([[.1],[.1],[.2],[.2],[.4],[.4],[.5],[.5],[.1],[.1],[.2],[.2]],dtype=float)
myImportedDatax2_np = np.array([[.1],[.2],[.1],[.2],[.1],[.2],[.1],[.2],[.4],[.5],[.4],[.5]],dtype=float)
combined_Imported_Data_x = np.append(myImportedDatax1_np, myImportedDatax2_np, axis=1)
myImportedDatay_np = np.array([[0],[0],[0],[0],[1],[1],[1],[1],[2],[2],[2],[2]],dtype=int)

def build_estimator(model_dir, model_type):
  x1 = tf.contrib.layers.real_valued_column("x1")
  x2 = tf.contrib.layers.real_valued_column("x2")

  wide_columns = [x1, x2]
  m = tf.contrib.learn.LinearClassifier(model_dir=model_dir, feature_columns=wide_columns)
  return m

def input_fn(input_batch, output_batch):
  inputs = {"x1": tf.constant(input_batch[:,0]), "x2": tf.constant(input_batch[:,1])}
  label = tf.constant(output_batch)
  print(inputs)
  print(label)
  print(input_batch)
  # Returns the feature columns and the label.
  return inputs, label

def train_and_eval(model_dir, model_type, train_steps, train_data, test_data):
  model_dir = tempfile.mkdtemp() if not model_dir else model_dir
  print("model directory = %s" % model_dir)
  m = build_estimator(model_dir, model_type)
  m.fit(input_fn=lambda: input_fn(combined_Imported_Data_x, myImportedDatay_np), steps=train_steps)
  results = m.evaluate(input_fn=lambda: input_fn(np.array([[.4, .1],[.4, .2]], dtype=float), np.array([[0], [0]], dtype=int)), steps=1)
  for key in sorted(results):
    print("%s: %s" % (key, results[key]))
  predictions = list(m.predict(input_fn=({"x1": tf.constant([[.1]]),"x2": tf.constant([[.1]])})))
 # print(predictions)

def main(_):
  train_and_eval(FLAGS.model_dir, FLAGS.model_type, FLAGS.train_steps,
                 FLAGS.train_data, FLAGS.test_data)

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.register("type", "bool", lambda v: v.lower() == "true")
  parser.add_argument(
      "--model_dir",
      type=str,
      default="",
      help="Base directory for output models."
  )
  parser.add_argument(
      "--model_type",
      type=str,
      default="wide_n_deep",
      help="Valid model types: {'wide', 'deep', 'wide_n_deep'}."
  )
  parser.add_argument(
      "--train_steps",
      type=int,
      default=200,
      help="Number of training steps."
  )
  parser.add_argument(
      "--train_data",
      type=str,
      default="",
      help="Path to the training data."
  )
  parser.add_argument(
      "--test_data",
      type=str,
      default="",
      help="Path to the test data."
  )
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

1 个答案:

答案 0 :(得分:1)

要解决这个具体问题,你可以添加以下类似于现有函数的输入函数,除了它返回None作为元组中的第二个元素

def input_fn_predict():
  inputs = {"x1": tf.constant([0.1]), "x2": tf.constant([0.2])}
  print(inputs)
  return inputs, None

在下一阶段,您可以使用以下方式调用它:

predictions = list(m.predict(input_fn=lambda: input_fn_predict()))

如果你注释掉你的印刷品,那么这应该有效。