基础Estimator以及自定义Estimator

基础Estimator

#--coding:utf-8--
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

tf.logging.set_verbosity(tf.logging.INFO)
mnist = input_data.read_data_sets()

#指定网络输入,所有这里指定的输入都会拼接起来作为整个网络的输入
feature_cloumns = [tf.feature_column.numeric_column("image", shape=[784])]


"""
#通过Tensorflow提供的封装好的Estimator定义网络模型。

  Arguments:
    features_cloumns:神经网络输入层需要的数据
    hidden_units:神经网络的结构 注意 DNNClassifier只能定义多层全连接神经网络 而hidden则给出了每一层隐藏层的节点个数
    n_classes:总共类目的数目
    optimizer:所使用的优化函数
    model_dir:将训练过程中loss的变化以及一些其他指标保存到此目录,通过TensorBoard可以可视化
"""
estimator = tf.estimator.DNNClassifier(
    feature_columns=feature_cloumns,
    hidden_units=[500],
    n_classes=10,
    optimizer=tf.train.AdamOptimizer(),
    model_dir="~~"
)

train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"image":mnist.train.images},
    y=mnist.train.labels.astype(np.int32),
    num_epochs=None,
    batch_size=128,
    shuffle=True
)

#训练模型 注意 此处没有定义损失函数 ,通过DNN定义的模型会使用交叉上作为损失函数
estimator.train(input_fn=train_input_fn, steps=10000)

#定义测试时的数据输入
test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"image":mnist.train.images},
    y=mnist.train.labels.astype(np.int32),
    num_epochs=1,
    batch_size=128,
    shuffle=False
)

accuracy_score = estimator.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest accuracy: %g %%" %(accuracy_score * 100))

 

自定义Estimator

# --coding:utf-8--
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

tf.logging.set_verbosity(tf.logging.INFO)


# 通过tf.layers来定义模型结构。可以使用原生态tf api或者其他高层封装。
def lenet(x, is_training):
    x = tf.reshape(x, shape=[-1, 28, 28, 1])

    net = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
    net = tf.layers.max_pooling2d(net, 2, 2)
    net = tf.layers.conv2d(net, 64, 3, activation=tf.nn.relu)
    net = tf.layers.max_pooling2d(net, 2, 2)
    net = tf.contrib.layers.flatten(net)
    net = tf.layers.dense(net, 1024)
    net = tf.layers.dropout(net, rate=0.4, training=is_training)
    return tf.layers.dense(net, 10)


"""
#自定义estimator中使用的模型。

  Arguments:
    features:输入函数中会提供的输入层张亮。这是一个字典,字典里的内容是通过tf.estimator.inputs.numpy_input_fn中x参数的内容指定的。
    label:正确分类标签,这个字段的内容是通过numpy_input_fn中y参数给出,
    mode:train/evaluate/predict
    params:字典  超参数
"""
def model_fn(featuers, labels, mode, params):
    predict = lenet(featuers["image"], mode == tf.estimator.ModeKeys.TRAIN)
    #如果在预测模式 只需要将结果返回
    if mode == tf.estimator.ModeKeys.PREDICT:
        #使用EstimatorSpec传递返回值,并通过predictions参数指定返回的结果
            return tf.estimator.EstimatorSpec(mode = mode, predictions={"result":tf.argmax(predict, 1)})
    #定义损失
    loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=predict, labels=labels))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=params["learning_rate"])

    #定义训练过程
    train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
    #定义评测标准
    eval_metric_ops = {"my_metric": tf.metrics.accuracy(tf.argmax(predict, 1), labels)}

    #返回模型训练过程需要使用的损失函数、训练过程和评测方法
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops)

mnist = input_data.read_data_sets("/path/to/MNIST_data", one_hot=False)

#通过自定义的方式生成Esttimator类,这里需要提供模型定义的函数并通过params参数指定模型定义时使用的超参数
model_params = {"learning_rate": 0.01}
estimator = tf.estimator.Estimator(model_fn=model_fn, params=model_params)

#训练
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"image": mnist.train.images},
    y=mnist.train.labels.astype(np.int32),
    num_epochs=None,
    batch_size=128,
    shuffle=True
)
estimator.train(input_fn=train_input_fn, steps=30000)
test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"image": mnist.test.images},
    y=mnist.test.labels.astype(np.int32),
    num_epochs=1,
    batch_size=128,
    shuffle=False
)
test_results = estimator.evaluate(input_fn=test_input_fn)

#这里的my_metric中的内容就是model_fn中eval_metric_ops定义的评测指标
accuracy_score = test_results["my_metric"]
print("\nTest accuracy: %g %%" % (accuracy_score * 100))

predict_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"image": mnist.test.images[:10]},
    num_epochs=1,
    shuffle=False
)
predictions = estimator.predict(input_fn=predict_input_fn)

for i, p in enumerate(predictions):
    print("Prediction %s: %s" % (i + 1, p["result"]))

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值