tensor意为张量,tensorflow通过tensor来进行一系列的操作
每运行一个模块需要创建一个新的InteractiveSession,不同的session之间的数据和运算相互独立
sess = tf.InteractiveSession() # 定义一个default的会话,每个会话相互独立,每个模型在一个会话中运行
x = tf.placeholder(tf.float32, [None, 784]) # x的tensor模块的预定义
Tensorflow算法设计、训练的核心步骤如下:1.定义算法公式 其中,tf.nn中包含了大量的神经网络组件2.定义loss,选定优化器optimizer,并指定优化器优化loss3.迭代地对数据进行训练4.在测试集(test dataset)或者验证集(validation dataset)上对准确率(correct_prediciton)进行accuracy评估
利用tensorflow实现softmax regression识别手写数字的代码如下:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape) # 55000x784, 55000x10
print(mnist.test.images.shape, mnist.test.labels.shape) # 10000x784, 10000x10
print(mnist.validation.images.shape, mnist.validation.labels.shape) # 5000x784, 5000x10
import tensorflow as tf
sess = tf.InteractiveSession() # 定义一个default的会话,每个会话相互独立,每个模型在一个会话中运行
x = tf.placeholder(tf.float32, [None, 784]) # x的tensor模块的预定义
# 定义长久保存tensor数据的Variable
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.Variable(tf.zeros([10]))
##################################################
# 1.定义算法公式
# tf.nn中包含了大量的神经网络组件
y = tf.nn.softmax(tf.matmul(x, W) + b) # 激活函数
##################################################
################################################################################################
# 2.定义loss,选定优化器optimizer,并指定优化器优化loss
# 定义loss function
y_ = tf.placeholder(tf.float32, [None, 10]) # 真实的概率分布
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 交叉熵
# 定义优化算法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run()
################################################################################################
################################################################################################
# 3.迭代地对数据进行训练
# 训练
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100) # 获取批量数据
train_step.run({x: batch_xs, y_: batch_ys})
################################################################################################
#4.在测试集(test dataset)或者验证集(validation dataset)上对准确率(correct_prediciton)进行accuracy评估
# 定义准确率
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # tf.argmax(y, 1)为所有预测的y中的最大值
# 统计全部样本的accuracy,首先利用tf.cast将之前correct_prediction输出的bool值转换为float32类型
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))