-
tensor数据类型,理解为一个向量,创建方法可是
tf.constant([1,2,3,4]) tf.Variable(tf.random_normal([3, 3], stddev=0.1))
-
shape,描述tensor的维度
a = tf.constant([ [1, 2], [3, 4] ]) print a.shape
-
打印tensor的值
b = tf.constant([1, 2]) c = a * b sess = tf.Session() #创建一个会话,资源的申请管理 sess.run(tf.Print(c, [c, b])) # c是目标节点,[c, b]是计算过程中需要打印的tensor
-
tf.reshape, 改变tensor的形状,但是元素的数量不能改变
aa = tf.reshape(a, [1, 4]) # [1, 2, 3, 4] aa = tf.reshape(a, [-1, 1]) # [[1], [2], [3], [4]] #只能有一个-1,-1表示那一维没有限制
-
tf.reduce_sum, 求和
r = tf.reduce_sum(a)#所有元素求和10 tf.reduce_sum(a, 1)#[3, 7] , 0按行求和, 1按列求和
-
tf.sign, tensor元素的符号
a = tf.constant([1.1, 0, -1.1]) b = tf.sign(a) # [1, 0, -1]
-
tf.cast, 类型转换
tf.cast(a, tf.int32) # [1, 0, -1]
-
tf.transpose 矩阵转置
output = tf.transpose(input, [1, 0, 2]) #这个就是一个三维向量的行列转置,1,0,2表示input的dim,input的shape是(3,4,5),完了就是(4,3,5)
-
tf.gather 取部分
b = tf.gather(a, [0, 1]) #取第一行和第二行
-
tf.matmul,矩阵相乘
-
tf.nn.embedding_lookup,embedding
em = tf.Variable(tf.random_uniform([vocab_size, emb_dim], -init_scope, init_scope) tf.nn.embedding_lookup(em, [1, 2])#em是所有词汇的编码,1,2是要编码的词的id,相当于查表操作
-
tf.train.Saver,保存模型,和增量训练
saver = tf.train.Saver() saver.save(sess, "model") #保存 saver.restore(sess, modelfile) # 从新加载,给图变量初始化,可以增量训练
-
tf.nn.softmax
softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
-
tf.FixedLenFeature
feature_types = {"left": tf.FixedLenFeature([10], tf.int64)} #10指向量的维度, int64指元素类型
-
tf.parse_example,数据预处理,和FixedLenFeature一起使用可以固定shape
features = tf.parse_example(batch_examples, features = features_types)
-
tf.train.Example,数据格式
feature = {"left": [1, 2, 3], "right": [5, 6, 7], "label": [0, 1]} example = tf.train.Example(features=tf.train.Features(feature=feature)) writer = tf.python_io.TFRecordWriter(tfrecord_name) writer.write(example.SerializeToString()) #转换成tf格式的数据
-
tf.TFRecordReader,读TF格式得数据
reader = tf.TFRecordReader() _, example = reader.read(file_queue)
-
tf.train.batch,把数据分成多个batch
batches = tf.train.batch([example], batch_size = batch_size, num_threads = 1, capacity = 10000 + batch_size * 2)
simple func:
def length(sequence):
used = tf.sign(tf.reduce_max(tf.abs(sequence), 2))
length = tf.reduce_sum(used, 1)
length = tf.cast(length, tf.int32)
return length
取2维中每行非零元素的个数