tensorflow之tf.contrib.learn Quickstart

一、载入必要的模块

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

import os
import urllib

import tensorflow as tf
import numpy as np

IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"

IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"

二、如果训练集跟测试集不存在,则先下载数据集

if not os.path.exists(IRIS_TRAINING):
  raw = urllib.urlopen(IRIS_TRAINING_URL).read()
  with open(IRIS_TRAINING,'w') as f:
    f.write(raw)

if not os.path.exists(IRIS_TEST):
  raw = urllib.urlopen(IRIS_TEST_URL).read()
  with open(IRIS_TEST,'w') as f:
    f.write(raw)

三、利用load_csv_with_header() 加载训练集跟测试集

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TRAINING,
    target_dtype=np.int,
    features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TEST,
    target_dtype=np.int,
    features_dtype=np.float32)

四、构造深度分类器
首先定义了模型的特征列,tf.contrib.layers.real_valued_column可以构造特征列

# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                            hidden_units=[10, 20, 10],
                                            n_classes=3,
                                            model_dir="/tmp/iris_model")

五、顶替数据输入张量

# Define the test inputs
def get_train_inputs():
  x = tf.constant(training_set.data)
  y = tf.constant(training_set.target)

  return x, y

六、Fit the DNNClassifier to the Iris Training Data

# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)

七、评估模型

# Define the test inputs
def get_test_inputs():
  x = tf.constant(test_set.data)
  y = tf.constant(test_set.target)

  return x, y

# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
                                     steps=1)["accuracy"]

print("\nTest Accuracy: {0:f}\n".format(accuracy_score))

八、新样本分类

def new_samples():
  return np.array(
    [[6.4, 3.2, 4.5, 1.5],
     [5.8, 3.1, 5.0, 1.7]], dtype=np.float32)

predictions = list(classifier.predict(input_fn=new_samples))

print(
    "New Samples, Class Predictions:    {}\n"
    .format(predictions))

源代码:

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

import os
import urllib

import numpy as np
import tensorflow as tf

# Data sets 
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"

IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"

def main():
  # If the training and test sets aren't stored locally, download them.
  if not os.path.exists(IRIS_TRAINING):
    raw = urllib.urlopen(IRIS_TRAINING_URL).read()
    with open(IRIS_TRAINING, "w") as f:
      f.write(raw)

  if not os.path.exists(IRIS_TEST):
    raw = urllib.urlopen(IRIS_TEST_URL).read()
    with open(IRIS_TEST, "w") as f:
      f.write(raw)

  # Load datasets.
  training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=IRIS_TRAINING,
      target_dtype=np.int,
      features_dtype=np.float32)
  test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=IRIS_TEST,
      target_dtype=np.int,
      features_dtype=np.float32)

  # Specify that all features have real-value data  
  feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

  # Build 3 layer DNN with 10, 20, 10 units respectively.
  classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                              hidden_units=[10, 20, 10],
                                              n_classes=3,
                                              model_dir="/tmp/iris_model")
  # Define the training inputs
  def get_train_inputs():
    x = tf.constant(training_set.data)
    y = tf.constant(training_set.target)

    return x, y

  # Fit model.
  classifier.fit(input_fn=get_train_inputs, steps=2000)

  # Define the test inputs
  def get_test_inputs():
    x = tf.constant(test_set.data)
    y = tf.constant(test_set.target)

    return x, y

  # Evaluate accuracy.
  accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
                                       steps=1)["accuracy"]

  print("\nTest Accuracy: {0:f}\n".format(accuracy_score))

  # Classify two new flower samples.
  def new_samples():
    return np.array(
      [[6.4, 3.2, 4.5, 1.5],
       [5.8, 3.1, 5.0, 1.7]], dtype=np.float32)

  predictions = list(classifier.predict(input_fn=new_samples))

  print(
      "New Samples, Class Predictions:    {}\n"
      .format(predictions))

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 很抱歉,TensorFlow 2.0 中已经删除了 `tensorflow.contrib` 模块,因此不能直接导入 `tensorflow.contrib.learn`。不过,您可以使用 `TensorFlow 2.0` 中内置的 `tf.keras` 模块,或者使用 `TensorFlow Hub` 中的预训练模型。 ### 回答2: 要导入tensorflow.contrib.learn,您需要使用tensorflow 2.0的兼容性模块tf.compat.v1。在TensorFlow 2.0中,tf.contrib模块已被移除。然而,通过tf.compat.v1模块,您仍然可以使用一些tensorflow.contrib模块中的功能。 您可以按照以下步骤来导入tensorflow.contrib.learn: 1. 导入所需的模块: ```python import tensorflow.compat.v1 as tf from tensorflow.compat.v1 import contrib ``` 2. 启用兼容性模式: ```python tf.disable_v2_behavior() ``` 3. 现在您可以使用tf.contrib.learn及其功能: ```python contrib.learn.Estimator(...) ``` 注意:虽然这种方法使您能够导入tensorflow.contrib.learn,但由于tf.compat.v1模块是为了向后兼容而设计的,因此它可能在将来的版本中被删除。因此,最好尽量使用tensorflow 2.0的原生API。如果您使用tensorflow.contrib.learn的功能非常重要,您可以考虑使用旧版本的tensorflow(如tensorflow 1.15)来支持它。 ### 回答3: 在TensorFlow 2.0中,已经不再支持`tensorflow.contrib.learn`这个模块。`tensorflow.contrib`是一个容纳实验性、不太稳定或较少使用的功能和功能组件的命名空间,而且在TensorFlow 1.X版本中是存在的。在TensorFlow 2.0中,TensorFlow团队已经将这些组件整合到了其他模块中,或者将它们作为独立的项目进行维护。因此,如果你想在TensorFlow 2.0中使用`tensorflow.contrib.learn`,你将无法直接导入它。 如果你仍然想使用类似于`tensorflow.contrib.learn`的某些功能,可以考虑以下方法: 1. 使用TensorFlow 2.0官方文档中提供的迁移指南,查找替代`tensorflow.contrib.learn`的功能或模块。官方文档通常会提供有关如何将旧版本的代码迁移到TensorFlow 2.0的详细说明。 2. 如果你只是需要用到一些机器学习算法,你可以考虑使用`scikit-learn`这个Python库。它是一个专门用于机器学习的库,提供了丰富的算法和工具,可以与TensorFlow 2.0进行结合使用。 总之,在TensorFlow 2.0中,将不再直接支持导入`tensorflow.contrib.learn`。如果你有特定的需求,需要找到替代的方法来实现你的目标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值