Tensorflow算法设计、训练的核心步骤

本文介绍了TensorFlow的核心步骤,强调了每个模块需在新的InteractiveSession中运行以保持数据和运算独立。以softmax回归识别手写数字为例,展示了TensorFlow的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,并指定优化器优化loss
3.迭代地对数据进行训练
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}))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值