# 用一个小例子教你入门机器学习框架TensorFlow

TensorFlow 是 Google 开发的一款用于机器学习的开源软件库。它能够在所有 Linux，Windows和 MacOS 平台上运行 CPU 和 GPU。Tensorflow 可用于设计，实现和训练深度学习模型。

### 第七步

``````import tensorflow as tf
import pandas as pd
from matplotlib import pyplot as plt

#从CSV读取数据
train_data = pd.read_csv("iris_training.csv", names=['f1', 'f2', 'f3', 'f4', 'f5'])
test_data = pd.read_csv("iris_test.csv", names=['f1', 'f2', 'f3', 'f4', 'f5'])

#将数据编码为独热
train_data['f5'] = train_data['f5'].map({0: [1, 0, 0], 1: [0, 1, 0], 2: [0, 0, 1]})
test_data['f5'] = test_data['f5'].map({0: [1, 0, 0], 1: [0, 1, 0], 2: [0, 0, 1]})

#分离训练数据
train_x = train_data[['f1', 'f2', 'f3', 'f4']]
train_y = train_data.ix[:, 'f5']

#分离测试数据
test_x = test_data[['f1', 'f2', 'f3', 'f4']]
test_y = test_data.ix[:, 'f5']

#输入和输出的文件夹
X = tf.placeholder(tf.float32, [None, 4])
Y = tf.placeholder(tf.float32, [None, 3])

#权重和偏差
weight = tf.Variable(tf.zeros([4, 3]))
bias = tf.Variable(tf.zeros([3]))

#运行激活函数后的输出
output = tf.nn.softmax(tf.matmul(X, weight) + bias)
#cost funciton
cost = tf.reduce_mean(tf.square(Y-output))
#train model

#检查成功与否
success = tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1))
#c计算准确率
accuracy = tf.reduce_mean(tf.cast(success, tf.float32))*100

#初始化变量
init = tf.global_variables_initializer()

#启动TensorFlow会话
with tf.Session() as sess:
costs = []
sess.run(init)
#训练模型1000次
for i in range(1000):
_,c = sess.run([train, cost], {X: train_x, Y: [t for t in train_y.as_matrix()]})
costs.append(c)

print("Training finished!")

#绘制代价图表
plt.plot(range(1000), costs)
plt.title("Cost Variation")
plt.show()
print("Accuracy: %.2f" %accuracy.eval({X: test_x, Y: [t for t in test_y.as_matrix()]}))