# 机器学习 - TensorFlow 框架初探

## 准备

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

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

```pip install virtualenv
virtualenv MLT_ENV```

```source MLT_ENV/bin/activate
deactivate```

`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

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```

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

## MNIST

`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”，将类别标签转换为向量，避免标签的数值关系。

```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))```

`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()```

```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()
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` ，即可打开

```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))  # 损失函数

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
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)```

OK! That's all! Enjoy it!