Future Frame Prediction for Anomaly Detection – A New Baseline
這是一篇CVPR2018的文章,是中科大高盛華團隊的工作,目前代碼已經放出。
以下都是我根據自身需求量身打造的,也供大家學習。
PS:看大神寫的代碼,優雅,簡潔,簡直就是一種享受。
1. [python] string.format() 格式化字符串
它通過{}和:來代替%。
print('training = {}'.format(tf.get_variable_scope().name))
功能非常之強大
:thumbsup::thumbsup::thumbsup::thumbsup::thumbsup:
2. [TF] tf.add_n([])
tf.add_n([p1, p2, p3….])函數是實現一個列表的元素的相加。就是輸入的對象是一個列表,列表裏的元素可以是向量,矩陣
g_loss = tf.add_n([lp_loss * lam_lp, gdl_loss * lam_gdl, adv_loss * lam_adv, flow_loss * lam_flow], name='g_loss')
???
3. [TF] tf.train.piecewise_constant()
g_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='g_step')
#分段改變學習率
g_lrate = tf.train.piecewise_constant(g_step, boundaries=BOUNDARIES, values=LRATE_G)
其中BOUNDARIES, LRATE_G都是列表
:thumbsup::thumbsup:
4. [TF] 關鍵字global_step的使用
終於徹底明白這傢伙的用途了。
global_step經常在滑動平均,學習速率變化的時候需要用到,這個參數在tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_steps)裏面有,系統會自動更新這個參數的值,從1開始。
舉例
global_steps = tf.Variable(0, trainable=False)
learning_rate = tf.train.exponential_decay(0.1, global_steps, 10, 2, staircase=False)
loss = tf.pow(w*x-y, 2)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_steps)
:thumbsup::thumbsup:
5. [TF] GPU
或者在 程序開頭
#在程序的開頭
os.environ['CUDA_VISIBLE_DEVICES'] = '0' #使用 GPU 0
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' # 使用 GPU 0,1
and
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)
# 使用allow_growth option,剛一開始分配少量的GPU容量,然後按需慢慢的增加,由於不會釋放
#內存,所以會導致碎片
and
# per_process_gpu_memory_fraction
gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.7)
config=tf.ConfigProto(gpu_options=gpu_options)
session = tf.Session(config=config, ...)
#設置每個GPU應該拿出多少容量給進程使用,0.7代表 70%
:thumbsup:
6.[python] configparaser 讀寫配置文件
以下列出如何讀
# set training hyper-parameters of different datasets
improt configparaser
config = configparser.ConfigParser()
assert config.read(args.config)
# 本代碼中用的ini文件
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('example.cfg')#cfg文件
其中配置文件格式如下:
[section]
name=value
或者
name: value
"#" 和";" 表示註釋
[DEFAULT] #設置默認的變量值,初始化
#舉例
[ped2]
# for lp loss. e.g, 1 or 2 for l1 and l2 loss, respectively)
L_NUM = 2
# the power to which each gradient term is raised in GDL loss
ALPHA_NUM = 1
# the percentage of the adversarial loss to use in the combined loss
LAM_ADV = 0.05
# the percentage of the lp loss to use in the combined loss
LAM_LP = 1
# the percentage of the GDL loss to use in the combined loss
LAM_GDL = 1
# the percentage of the different frame loss
LAM_FLOW = 2
# For gray scale video, such as Ped2 and Ped1, learning rate of G and D star from 1e-4 and 1e-5, respectively.
LRATE_G = [0.0001, 0.00001]
LRATE_G_BOUNDARIES = [7000]
LRATE_D = [0.00001, 0.000001]
LRATE_D_BOUNDARIES = [7000]
#如何獲取之中的值,舉個例
const.L_NUM = config.getint(const.DATASET, 'L_NUM')
:thumbsup::thumbsup::thumbsup:
7. [numpy] concatenate()
numpy提供了numpy.concatenate((a1,a2,…), axis=0)函數。能夠一次完成多個數組的拼接。其中a1,a2,…是數組類型的參數
a=np.array([1,2,3])
b=np.array([11,22,33])
c=np.array([44,55,66])
np.concatenate((a,b,c),axis=0)
# 默認情況下,axis=0可以不寫
array([ 1, 2, 3, 11, 22, 33, 44, 55, 66])
#對於一維數組拼接,axis的值不影響最後的結果
concatenate()效率高,適合大規模的數據拼接
https://blog.csdn.net/zyl1042635242/article/details/43162031
8.[TF] tf.data API
這個地方要學的太多了,收穫滿滿~~
:thumbsup::thumbsup::thumbsup::thumbsup::thumbsup:
9. [python] 類__call__
Python中的函數是一級對象。這意味着Python中的函數的引用可以作爲輸入傳遞到其他的函數/方法中,並在其中被執行。
而Python中類的實例(對象)可以被當做函數對待。也就是說,我們可以將它們作爲輸入傳遞到其他的函數/方法中並調用他們,正如我們調用一個正常的函數那樣。而類中__call__()
函數的意義正在於此。爲了將一個類實例當做函數調用,我們需要在類中實現__call__()
方法。也就是我們要在類中實現如下方法:def __call__(self, *args)
。這個方法接受一定數量的變量作爲輸入。
假設x是X類的一個實例。那麼調用x.__call__(1,2)
等同於調用x(1,2)
。這個實例本身在這裏相當於一個函數。
class X(object):
def __init__(self, a, b, range):
self.a = a
self.b = b
self.range = range
def __call__(self, a, b):
self.a = a
self.b = b
print('__call__ with ({}, {})'.format(self.a, self.b))
def __del__(self, a, b, range):
del self.a
del self.b
del self.range
#
xInstance = X(1, 2, 3)
xInstance(1,2)#作爲函數使用
https://blog.csdn.net/yaokai_assultmaster/article/details/70256621
:thumbsup::thumbsup::thumbsup::thumbsup:
10.[numpy] np.identity()
兩個函數的原型爲:
np.identity(n, dtype=None)
np.eye(N, M=None, k=0, dtype=<type ‘float’>)
np.identity只能創建方形矩陣
np.eye可以創建矩形矩陣,且k值可以調節,爲1的對角線的位置偏離度,0居中,1向上偏離1,2偏離2,以此類推,-1向下偏離。值絕對值過大就偏離出去了,整個矩陣就全是0了
:thumbsup:
昨晚失眠,今天早點回去。。。先寫這麼多。
2018-04-10 23:01
11.[TF] Gradient Loss
這個地方取自paperDeep multi-scale video prediction beyond mean square error, 代碼github
def gradient_loss(gen_frames, gt_frames, alpha):
"""
Calculates the sum of GDL losses between the predicted and ground truth frames.
@param gen_frames: The predicted frames at each scale.
@param gt_frames: The ground truth frames at each scale
@param alpha: The power to which each gradient term is raised.
@return: The GDL loss.
"""
# calculate the loss for each scale
# create filters [-1, 1] and [[1],[-1]] for diffing to the left and down respectively.
#水平和垂直方向各自3個卷積核,即每次只對一個通道進行卷積求梯度。水平卷積核大小[1x2x3]比如[[[-1,0,0],
#[1,0,0]]]是R通道 1對應h方向,2對應w方向,3對應channel方向
#垂直的[2x1x3] 同上
channels = gen_frames.get_shape().as_list()[-1]
pos = tf.constant(np.identity(channels), dtype=tf.float32) # 3 x 3
neg = -1 * pos
filter_x = tf.expand_dims(tf.stack([neg, pos]), 0) # [-1, 1]
filter_y = tf.stack([tf.expand_dims(pos, 0), tf.expand_dims(neg, 0)]) # [[1],[-1]]
strides = [1, 1, 1, 1] # stride of (1, 1)
padding = 'SAME'
#每個的大小爲height*width*3
gen_dx = tf.abs(tf.nn.conv2d(gen_frames, filter_x, strides, padding=padding))
gen_dy = tf.abs(tf.nn.conv2d(gen_frames, filter_y, strides, padding=padding))
gt_dx = tf.abs(tf.nn.conv2d(gt_frames, filter_x, strides, padding=padding))
gt_dy = tf.abs(tf.nn.conv2d(gt_frames, filter_y, strides, padding=padding))
grad_diff_x = tf.abs(gt_dx - gen_dx)
grad_diff_y = tf.abs(gt_dy - gen_dy)
# condense into one tensor and avg
#return gen_dx, gen_dy
return tf.reduce_mean(grad_diff_x ** alpha + grad_diff_y ** alpha)
其中 gen_frames, gt_frames都是tensor.這個必須是對3通道的圖像進行計算,即水平垂直個3個邊緣卷積核分別都RGB通道進行計算。