Tensorflow简介

本文介绍了一个使用TensorFlow实现的单隐藏层多层感知机(MLP)分类器,该分类器针对MNIST手写数字数据集进行了训练。通过构建计算图,设置占位符来接收输入数据,并定义权重与偏置变量进行线性转换,最后通过softmax函数获得预测概率。使用交叉熵损失函数和梯度下降优化器来最小化误差。

Tensorflow解析

系统角度

TF系统架构

实现角度

Computational Graph Architecture

Data Flow Graph

运用角度

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A one-hidden-layer-MLP MNIST-classifier. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import the training data (MNIST)
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# Possibly download and extract the MNIST data set.
# Retrieve the labels as one-hot-encoded vectors.
mnist = input_data.read_data_sets("/tmp/mnist", one_hot=True)
# Create a new graph
graph = tf.Graph()
# Set our graph as the one to add nodes to
with graph.as_default():
    # Placeholder for input examples (None = variable dimension)
    examples = tf.placeholder(shape=[None, 784], dtype=tf.float32)
    # Placeholder for labels
    labels = tf.placeholder(shape=[None, 10], dtype=tf.float32)
    weights =tf.Variable(tf.truncated_normal(shape=[784,10], stddev=0.1))
    bias = tf.Variable(tf.constant(0.1, shape=[10]))
    # Apply an affine transformation to the input features
    logits = tf.matmul(examples, weights) + bias
    estimates = tf.nn.softmax(logits)
    # Compute the cross-entropy
    cross_entropy = -tf.reduce_sum(labels * tf.log(estimates), reduction_indices=[1])
    # And finally the loss
    loss = tf.reduce_mean(cross_entropy)
    # Create a gradient-descent optimizer that minimizes the loss.
    # We choose a learning rate of 0.01
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
    # Find the indices where the predictions were correct
    correct_predictions = tf.equal(tf.argmax(estimates, dimension=1),
                                   tf.argmax(labels, dimension=1))
    accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
with tf.Session(graph=graph) as session:
    tf.initialize_all_variables().run()
    for step in range(1001):
        example_batch, label_batch = mnist.train.next_batch(100)
        feed_dict = {examples: example_batch, labels: label_batch}
        if step % 100 == 0:
            _, loss_value, accuracy_value = session.run(
                                      [optimizer, loss, accuracy],
                                      feed_dict=feed_dict)
            print("Loss at time {0}: {1}".format(step, loss_value))
            print("Accuracy at time {0}: {1}".format(step, accuracy_value))
        else:
            optimizer.run(feed_dict)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值