tensorflow基本语法

  1. tensor数据类型,理解为一个向量,创建方法可是

    tf.constant([1,2,3,4])
    tf.Variable(tf.random_normal([3, 3], stddev=0.1))
    
  2. shape,描述tensor的维度

    a = tf.constant([ [1, 2], [3, 4] ])
    print a.shape
    
  3. 打印tensor的值

    b = tf.constant([1, 2])
    c = a * b
    sess = tf.Session()   #创建一个会话,资源的申请管理
    sess.run(tf.Print(c, [c, b])) # c是目标节点,[c, b]是计算过程中需要打印的tensor 
    
  4. 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表示那一维没有限制
    
  5. tf.reduce_sum, 求和

    r = tf.reduce_sum(a)#所有元素求和10
    tf.reduce_sum(a, 1)#[3, 7] , 0按行求和, 1按列求和
    
  6. tf.sign, tensor元素的符号

    a = tf.constant([1.1, 0, -1.1])
    b = tf.sign(a) # [1, 0, -1]
    
  7. tf.cast, 类型转换

    tf.cast(a, tf.int32) # [1, 0, -1]
    
  8. tf.transpose 矩阵转置

    output = tf.transpose(input, [1, 0, 2]) #这个就是一个三维向量的行列转置,1,0,2表示input的dim,input的shape是(3,4,5),完了就是(4,3,5)
    
  9. tf.gather 取部分

    b = tf.gather(a, [0, 1])  #取第一行和第二行
    
  10. tf.matmul,矩阵相乘

  11. 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,相当于查表操作
    
  12. tf.train.Saver,保存模型,和增量训练

    saver = tf.train.Saver()
    saver.save(sess, "model") #保存
    saver.restore(sess, modelfile) # 从新加载,给图变量初始化,可以增量训练
    
  13. tf.nn.softmax

    softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
    
  14. tf.FixedLenFeature

       feature_types = {"left": tf.FixedLenFeature([10], tf.int64)} #10指向量的维度, int64指元素类型
    
  15. tf.parse_example,数据预处理,和FixedLenFeature一起使用可以固定shape

    features = tf.parse_example(batch_examples, features = features_types)
    
  16. 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格式的数据
    
  17. tf.TFRecordReader,读TF格式得数据

    reader = tf.TFRecordReader()
    _, example = reader.read(file_queue)
    
  18. 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维中每行非零元素的个数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值