人工智能 - TensorFlow 框架初探

欢迎Follow我的GitHub

本文地址:http://blog.csdn.net/caroline_wendy/article/details/77639394

框架:Python + TensorFlow
知识:工程配置 + HelloWorld + MNIST

本文源码的GitHub地址

TensorFlow


准备

Fork TensorFlow的工程,并下载,转换远端Git地址

git remote set-url origin https://github.com/SpikeKing/tensorflow.git

创建Python工程MachineLearningTutorial,使用 virtualenv 创建虚拟环境

pip install virtualenv
virtualenv MLT_ENV

激活或关闭的命令

source MLT_ENV/bin/activate
deactivate

安装TensorFlow的库,使用阿里云的源

pip install TensorFlow -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com

导出库的版本,及全部安装

pip freeze>requirements.txt
pip install -r requirements.txt

Hello World

切换Python的解释器(Interpreter)

Interpreter

HelloWorld

import tensorflow as tf

hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print sess.run(hello)

a = tf.constant(10)
b = tf.constant(32)
print sess.run(a + b)

输出

Hello, TensorFlow!
42

避免cpu_feature_guard警告

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

MNIST

路径:tensorflow/examples/tutorials/mnist/mnist_softmax.py

加载MNIST数据,默认存放于tmp文件夹,标签使用one-hot模式

mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

one-hot的值,如下:[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.],表示标签“7”,将类别标签转换为向量,避免标签的数值关系。

创建变量,placeholder表示输入数据、Variable表示可变参数,最终公式是y = x * W + b,y_表示真实标签(Ground Truth)

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b 
y_ = tf.placeholder(tf.float32, [None, 10])

计算交叉熵,即损失函数,labels表示真实标签,logits表示预估标签

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

等价于

sc2 = tf.reduce_sum(-1 * (labels_ * tf.log(tf.nn.softmax(labels))), reduction_indices=[1])

梯度下降的方式,优化交叉熵

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

创建交互会话,初始化全部可变参数

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

每次取出100张图片,进行训练,在Session中执行train_step公式,feed_dict输入参数(placeholder),按批次(batch)训练

for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

输出一维列表最大值的索引(argmax),进行比较(equal),再讲Bool值转为Float(cast),全部求平均(reduce_mean),就是准确率的计算公式

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

在Session中执行accuracy公式,feed_dict输入参数(placeholder),数据源是测试集

print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                    y_: mnist.test.labels}))

脚本参数是data_dir,在main函数中,则是FLAGS.data_dir,默认存放于临时目录(tmp),在 tf.app.run()中执行,FLAGS表示指定的参数,如--learning_rate 20,unparsed表示未指定的参数,随意输入的参数。

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                        help='Directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Mac系统中,tmp存放隐藏文件,在终端的home目录中,输入open /tmp,即可打开

tmp

完整的MNIST代码,及注释

FLAGS = None  # 全局变量


def main(_):
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)  # 加载数据源

    x = tf.placeholder(tf.float32, [None, 784])  # 数据输入
    W = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.zeros([10]))
    y = tf.matmul(x, W) + b

    y_ = tf.placeholder(tf.float32, [None, 10])  # 标签输入

    cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))  # 损失函数
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)  # 优化器

    sess = tf.InteractiveSession()  # 交互会话
    tf.global_variables_initializer().run()  # 初始化变量

    # 训练模型
    for _ in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

    # 验证模型
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                        y_: mnist.test.labels}))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()  # 设置参数data_dir
    parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                        help='Directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

工程配置 + HelloWorld + MNIST

OK! That’s all! Enjoy it!

猜你喜欢

转载自blog.csdn.net/u012515223/article/details/77639394