Python學習記錄-tensorflow train

numpy

  1. np.identity
    返回一個單位矩陣
  2. np.concatenate
    https://img-blog.csdn.net/20180414163140310?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0tvbF9tb2dvcm92/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70image_1cptvo746g3farv1glq14v31kos9.png-36.3kB
    axis = i, 則在第i維上發生變化;
  3. np.transpose
    轉置

python

  1. callable
    callable() 函數用於檢查一個對象是否是可調用的。如果返回True,object仍然可能調用失敗;但如果返回False,調用對象ojbect絕對不會成功。
    對於函數, 方法, lambda 函式, 類, 以及實現了 __call__ 方法的類實例, 它都返回 True。

tensorflow

  1. nn.conv2d

    tf.nn.conv2d(input_batch, kernel,\
    strides=[image_batch_size_stride, \
            image_height_stride, \
            image_width_stride,\
            image_channels_stride], padding='SAME')
    
  2. tf.variable_scope
    tf.variable_scope, 用於定義創建變量(層)的操作的上下文管理器;

    with tf.variable_scope("foo"):
        with tf.variable_scope("bar"):
            v = tf.get_variable("v", [1])
            assert v.name == "foo/bar/v:0"
    
  3. tf.summary

    tf.summary.histogram(tags, values, collections=None, name=None)
    # 用來顯示直方圖信息,一般用來顯示訓練過程中變量的分佈情況
    
    tf.summary.scalar(tags, values, collections=None, name=None)
    # 用來顯示標題信息,一般在畫loss,accuary時會用到
    
  4. tf.cast
    將x的數據格式轉化成dtype.例如,原來x的數據格式是bool,
    那麼將其轉化成float以後,就能夠將其轉化成0和1的序列。反之也可以

    a = tf.Variable([1,0,0,1,1])
    b = tf.cast(a,dtype=tf.bool)
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    print(sess.run(b))
    #[ True False False  True  True]
    
  5. tf.ConfigProto

    # tf.ConfigProto()的參數
    log_device_placement=True : 是否打印設備分配日誌
    allow_soft_placement=True : 如果你指定的設備不存在,允許TF自動分配設備   
    tf.ConfigProto(log_device_placement=True,allow_soft_placement=True)
    
  6. tf.truncated_normal_initalizer
    這是神經網絡權重和過濾器的推薦初始值。

    tf.truncated_normal_initializer 
    從截斷的正態分佈中輸出隨機值。
    生成的值服從具有指定平均值和標準偏差的正態分佈,
    如果生成的值大於平均值2個標準偏差的值則丟棄重新選擇。
    
  7. sess.run

  8. tf.train.Coordinator()
    TensorFlow提供了兩個類來實現對Session中多線程的管理:tf.Coordinator和 tf.QueueRunner,這兩個類往往一起使用。
    Coordinator類用來管理在Session中的多個線程,可以用來同時停止多個工作線程並且向那個在等待所有工作線程終止的程序報告異常,該線程捕獲到這個異常之後就會終止所有線程。使用 tf.train.Coordinator()來創建一個線程管理器(協調器)對象。

    # -*- coding:utf-8 -*-
    import tensorflow as tf
    import numpy as np
     
    # 樣本個數
    sample_num=5
    # 設置迭代次數
    epoch_num = 2
    # 設置一個批次中包含樣本個數
    batch_size = 3
    # 計算每一輪epoch中含有的batch個數
    batch_total = int(sample_num/batch_size)+1
     
    # 生成4個數據和標籤
    def generate_data(sample_num=sample_num):
        labels = np.asarray(range(0, sample_num))
        images = np.random.random([sample_num, 224, 224, 3])
        print('image size {},label size :{}'.format(images.shape, labels.shape))
        return images,labels
     
    def get_batch_data(batch_size=batch_size):
        images, label = generate_data()
        # 數據類型轉換爲tf.float32
        images = tf.cast(images, tf.float32)
        label = tf.cast(label, tf.int32)
     
        #從tensor列表中按順序或隨機抽取一個tensor準備放入文件名稱隊列
        input_queue = tf.train.slice_input_producer([images, label], num_epochs=epoch_num, shuffle=False)
     
        #從文件名稱隊列中讀取文件準備放入文件隊列
        image_batch, label_batch = tf.train.batch(input_queue, batch_size=batch_size, num_threads=2, capacity=64, allow_smaller_final_batch=False)
        return image_batch, label_batch
     
    image_batch, label_batch = get_batch_data(batch_size=batch_size)
     
     
    with tf.Session() as sess:
     
        # 先執行初始化工作
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
     
        # 開啓一個協調器
        coord = tf.train.Coordinator()
        # 使用start_queue_runners 啓動隊列填充
        threads = tf.train.start_queue_runners(sess, coord)
     
        try:
            while not coord.should_stop():
                print '************'
                # 獲取每一個batch中batch_size個樣本和標籤
                image_batch_v, label_batch_v = sess.run([image_batch, label_batch])
                print(image_batch_v.shape, label_batch_v)
        except tf.errors.OutOfRangeError:  #如果讀取到文件隊列末尾會拋出此異常
            print("done! now lets kill all the threads……")
        finally:
            # 協調器coord發出所有線程終止信號
            coord.request_stop()
            print('all threads are asked to stop!')
        coord.join(threads) #把開啓的線程加入主線程,等待threads結束
        print('all threads are stopped!')
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章