Tensorflow API 笔记
来源:互联网 发布:淘宝抠图 编辑:程序博客网 时间:2024/06/07 03:45
Hello World 的实现:
import tensorflow as tf# Create TensorFlow object called hello_constanthello_constant = tf.constant('Hello World!')with tf.Session() as sess: # Run the tf.constant operation in the session output = sess.run(hello_constant) print(output)
在Tensorflow中,所有的数据(字符串,数字……)都被封装为一个Tensorflow对象,API操作均针对封装的tf对象;
tf.constant()
在 hello_constant = tf.constant(‘Hello World!’) 中,tf.constant()保存的为一常数值对象,hello_constant 是一个 0 维度的字符串 tensor;
数值、多维数组等等都可以保存为constant常量:
# A is a 0-dimensional int32 tensorA = tf.constant(1234) # B is a 1-dimensional int32 tensorB = tf.constant([123,456,789]) # C is a 2-dimensional int32 tensorC = tf.constant([ [123,456,789], [222,333,444] ])
Session
TensorFlow 的 api 构建在 computational graph 的概念上,它是一种对数学运算过程进行可视化的方法; 当搭建完该graph后,需要一个接口运行graph环境,该接口就是 tf.Session(),方法则是 Session().run(graph);with tf.Session() as sess:output = sess.run(hello_constant)
即将搭建好的hello_constant 通过sess.run()运行,并返回结果;
tf.placeholder()
tf.placeholder()是TF里的占位符,可以用于申明非常量;Session 的 feed_dict
作用有些类似于Python自带的 .format(),可以在sess运行过程中为之前申明的非常量赋值;
import tensorflow as tfdef run(): output = None x = tf.placeholder(tf.int32) with tf.Session() as sess: # TODO: Feed the x tensor 123 output = sess.run(x, feed_dict={x:'123'}) return output
如果传入 feed_dict 的数据与 tensor 类型不符,就无法被正确处理,会得到 “ValueError: invalid literal for…”。
- tf.Variable()
设置一个 tensor,其初始值可以被改变,就像普通的 Python 变量一样。该 tensor 把它的状态存在 session 里,所以必须手动初始化它的状态。初始化函数为: tf.global_variables_initializer()
tf.global_variables_initializer() 会返回一个操作,它会从 graph 中初始化所有的 TensorFlow 变量。
- Tensorflow 加、减、乘、除
如下:
x = tf.add(5, 2) # 7x = tf.subtract(10, 4) # 6y = tf.multiply(2, 5) # 10y = tf.divide(6, 2) #3
计算中需要注意数据类型的问题,即要求运算各方均为统一类型(int\float32\float64),以下代码会报错:
tf.subtract(tf.constant(2.0),tf.constant(1)) # Fails with ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32:
此时需要使用tf.cast(data, type)对数据类型进行转换;eg:
import tensorflow as tf# TODO: Convert the following to TensorFlow:x = tf.constant(10)y = tf.constant(2)z = tf.subtract(tf.divide(x,y), tf.cast(tf.constant(1), tf.float64))# TODO: Print z from a sessionwith tf.Session() as sess: output = sess.run(z)print(output)
- tf.matmul()
Tf中矩阵乘法运算需要使用 tf.matmul() ,而不是tf.multiply();
另外还有:
累加函数:
x = tf.reduce_sum([1, 2, 3, 4, 5]) # 15
对数函数: 返回所输入值的自然对数
x = tf.log(100) # 4.60517
Tensorflow中的 softmax函数
Tf中在分类问题上采用的是softmax函数,该函数为:
softmax 函数将每个单元的输出压缩到 0 和 1 之间。但 softmax 函数在拆分输出时,会使输出之和等于 1。softmax 函数的输出等于分类概率分布,显示了任何类别为真的概率。
softmax函数在Tensorflow里的API为:tf.nn.softmax() ,直接调用即可;
import tensorflow as tfdef run(): output = None logit_data = [2.0, 1.0, 0.1] logits = tf.placeholder(tf.float32) # TODO: Calculate the softmax of the logits softmax = tf.nn.softmax(logits) with tf.Session() as sess: # TODO: Feed in the logit data output = sess.run(softmax, feed_dict = {logits: logit_data} ) return output
- TensorFlow 中的交叉熵函数(Cross Entropy)
交叉熵数学表达式:
在Tensorflow中,可以采用
cross_entropy = -tf.reduce_sum(tf.multiply(pi, tf.log(pi_hat)))
import tensorflow as tfsoftmax_data = [0.7, 0.2, 0.1]one_hot_data = [1.0, 0.0, 0.0]softmax = tf.placeholder(tf.float32)one_hot = tf.placeholder(tf.float32)# TODO: Print cross entropy from sessioncross_entropy = -tf.reduce_sum(tf.multiply(one_hot, tf.log(softmax)))with tf.Session() as sess: output = sess.run(cross_entropy, feed_dict ={one_hot: one_hot_data, softmax: softmax_data})
- tf.truncated_normal()
tf.truncated_normal((row,column)) 返回一个 tensor,它的随机值取自一个正态分布,并且它们的取值会在这个正态分布平均值的两个标准差之内。
运行该tensor可以获得row行column列矩阵:
>>> weights = tf.truncated_normal((3,4))>>> with tf.Session() as session: session.run(weights)... ... array([[ 1.61371827, -0.5563615 , -0.87211525, -0.20940897], [ 0.93897802, -0.80794263, 0.96629286, -0.1466012 ], [-1.06747437, -0.5541333 , 0.30477989, -0.21800314]], dtype=float32)