深层神经网络实现–step by step 入门TensorFlow(二)
标签:tensorflow
我们将采用Jupyter notebook交互式编程的方式,通过一步步代码的讲解,学习Tensorflow 编程。推荐使用Jupyter notebook作为开发环境按照文中的代码step by step 的学习。
文章列表:
Tensorflow基础知识与神经网络构建–step by step 入门TensorFlow(一)
深层神经网络实现–step by step 入门TensorFlow(二)
MNIST 数字识别和数据持久化–step by step 入门TensorFlow(三)
损失函数
神经网络模型的效果和优化目标是通过损失函数来定义的
如果用一个向量作为分类结果(比如[0,0,0,1,0]识别为第4类),那如何判断输出向量与期望的向量有多接近呢?
交叉熵是最常用的评判标准之一,它刻画了两个概率分布之间的距离。而softmax()函数可以把把输出变为概率分布。
下面是交叉熵的实现,交叉熵与回归一起可以tf.nn.softmax_cross_entropy_with_logits().
其中tf.clip_by_value的展示
import tensorflow as tf
# cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10,1.0)))
#tf.nn.softmax_cross_entropy_with_logits(y,y_)
v = tf.constant([[1.0,2.0,3.0], [4.0,5.0,6.0]])
print(tf.clip_by_value(v,2.5,4.5).eval())
[[ 2.5 2.5 3. ]
[ 4. 4.5 4.5]]
求平均的tf.reduce_mean()函数使用方法
with tf.Session() as sess:
print(tf.reduce_mean(v).eval())
3.5
我们也可以自定义损失函数。tf.greater(v1,v2)遍历向量做大小判断,大于为true,tf.select()根据条件选择取那个队列中的元素。
import tensorflow as tf
v1 = tf.constant([2,3,8