基础Estimator以及自定义Estimator

基础Estimator以及自定义Estimator基础 Estimator coding utf 8importnumpy examples tutorials mnistimporti datatf logging set verbosity tf logging INFO mnist input data read

基础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"])) 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199502.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月20日 下午12:50
下一篇 2026年3月20日 下午12:51


相关推荐

  • linux中看挂载的磁盘用什么命令,如何查看Linux挂载磁盘

    linux中看挂载的磁盘用什么命令,如何查看Linux挂载磁盘通常我们都使用命令查看 Linux 系统中挂载的磁盘 其实除了这种方法外 还有很多方法能够查看 Linux 挂载磁盘 下面小编就给大家介绍下 Linux 中如何查看挂载磁盘 第一种方法 使用 df 命令 例如 代码如下 orientalson home dfFilesystem blocksUsedAv Mountedon dev sda4366

    2026年3月17日
    2
  • 计算机 原码、反码、补码(相互转化)

    计算机 原码、反码、补码(相互转化)一 基本概念在计算机系统中 数值一律用补码来表示和存储 原因在于 使用补码 可以将符号位和数值域统一处理 同时 加法和减法也可以用补码统一处理 此外 补码与原码相互转换 其运算过程是相同的 不需要额外的硬件电路 原码 二进制表示 二进制首位是符号位 0 为正 1 为负 反码 正数 反码和原码一样 负数 符号位不变 其他各位取反 补码 正数 补码和原码一样 负数 反码末位加 1 有进位则进位 但不改变符号位二 举个例子 假设是字节长度为 8 位 正数 1

    2026年3月17日
    2
  • struts2的response的contentType设置

    struts2的response的contentType设置服务器端发送到客户端,提示保存还是打开?       response.setContentType(“text/html;charset=utf-8”)发送到客户端格式不正确。使用ajaxUpload插件的时候,strust2返回application/json格式的数据,但是ajaxUpload要求返回text/html,这样就需要在配置文件中配置contentType项。

    2022年7月19日
    18
  • 五、OpenClaw 的控制台(Dashboard)。

    五、OpenClaw 的控制台(Dashboard)。

    2026年3月13日
    2
  • java常量表示_形参可以是常量吗

    java常量表示_形参可以是常量吗万千封印我知道编译器需要在编译时知道表达式才能编译一个开关,但是为什么foo.ba_常数不是呢?虽然从字段初始化后执行的任何代码的角度来看,它们都是常量,但它们不是编译时间常数在JLS所要求的意义上;见§15.28常量表达式的规格常数表达式1..这指的是§4.12.4最后变量它将“常量变量”定义为:我们称一个变量为原始类型或类型字符串,它是最终变量,并使用编译时常量表达式(§15.28)初始化为常…

    2026年4月18日
    8
  • java request get 请求乱码解决

    java request get 请求乱码解决

    2020年11月19日
    186

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号