tensorflow slim 代碼使用

這篇文章是借鑒很多博文的糟袁,作為一個關(guān)于slim庫的總結(jié)

導入slim 模塊
import tensorflow.contrib.slim as slim
定義slim的變量
 Model Variables
weights = slim.model_variable('weights',
                              shape=[10, 10, 3 , 3],
                              initializer=tf.truncated_normal_initializer(stddev=0.1),
                              regularizer=slim.l2_regularizer(0.05),
                              device='/CPU:0')
model_variables = slim.get_model_variables()
 
# Regular variables
my_var = slim.variable('my_var',
                       shape=[20, 1],
                       initializer=tf.zeros_initializer())
regular_variables_and_model_variables = slim.get_variables()

這里model_variable是作為模型參數(shù)保存的,variable是局部變量,不會保存。

slim中實現(xiàn)一個層
input = ...
net = slim.conv2d(input, 128, [3, 3], scope='conv1_1')
#代碼重用
net = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], scope='conv3')
net = slim.max_pool2d(net, [2, 2], scope='pool2')
#處理不同參數(shù)情況
x = slim.fully_connected(x, 32, scope='fc/fc_1')
x = slim.fully_connected(x, 64, scope='fc/fc_2')
x = slim.fully_connected(x, 128, scope='fc/fc_3')
or
slim.stack(x, slim.fully_connected, [32, 64, 128], scope='fc')

# 普通方法:
x = slim.conv2d(x, 32, [3, 3], scope='core/core_1')
x = slim.conv2d(x, 32, [1, 1], scope='core/core_2')
x = slim.conv2d(x, 64, [3, 3], scope='core/core_3')
x = slim.conv2d(x, 64, [1, 1], scope='core/core_4')
 
# 簡便方法:
slim.stack(x, slim.conv2d, [(32, [3, 3]), (32, [1, 1]), (64, [3, 3]), (64, [1, 1])], scope='core')
不同層的代碼復用函數(shù)
Layer TF-Slim
BiasAdd slim.bias_add
BatchNorm slim.batch_norm
Conv2d slim.conv2d
Conv2dInPlane slim.conv2d_in_plane
Conv2dTranspose (Deconv) slim.conv2d_transpose
FullyConnected slim.fully_connected
AvgPool2D slim.avg_pool2d
Dropout slim.dropout
Flatten slim.flatten
MaxPool2D slim.max_pool2d
OneHotEncoding slim.one_hot_encoding
SeparableConv2 slim.separable_conv2d
UnitNorm slim.unit_norm
定義相同參數(shù)的簡化
with slim.arg_scope([slim.conv2d], padding='SAME',
                      weights_initializer=tf.truncated_normal_initializer(stddev=0.01)
                      weights_regularizer=slim.l2_regularizer(0.0005)):
    net = slim.conv2d(inputs, 64, [11, 11], scope='conv1')
    net = slim.conv2d(net, 128, [11, 11], padding='VALID', scope='conv2')
    net = slim.conv2d(net, 256, [11, 11], scope='conv3')

#arg_scope的嵌套

with slim.arg_scope([slim.conv2d, slim.fully_connected],
                      activation_fn=tf.nn.relu,
                      weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
                      weights_regularizer=slim.l2_regularizer(0.0005)):
  with slim.arg_scope([slim.conv2d], stride=1, padding='SAME'):
    net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1')
    net = slim.conv2d(net, 256, [5, 5],
                      weights_initializer=tf.truncated_normal_initializer(stddev=0.03),
                      scope='conv2')
    net = slim.fully_connected(net, 1000, activation_fn=None, scope='fc')
訓練模型
loss = slim.losses.softmax_cross_entropy(predictions, labels)
#自定義loss模型
# Define the loss functions and get the total loss.
classification_loss = slim.losses.softmax_cross_entropy(scene_predictions, scene_labels)
sum_of_squares_loss = slim.losses.sum_of_squares(depth_predictions, depth_labels)
pose_loss = MyCustomLossFunction(pose_predictions, pose_labels)
slim.losses.add_loss(pose_loss) # Letting TF-Slim know about the additional loss.
 
# The following two ways to compute the total loss are equivalent:
regularization_loss = tf.add_n(slim.losses.get_regularization_losses())
total_loss1 = classification_loss + sum_of_squares_loss + pose_loss + regularization_loss
slim讀取保存模型的方法
# Create some variables.
v1 = slim.variable(name="v1", ...)
v2 = slim.variable(name="nested/v2", ...)
...
 
# Get list of variables to restore (which contains only 'v2').
variables_to_restore = slim.get_variables_by_name("v2")
 
# Create the saver which will be used to restore the variables.
restorer = tf.train.Saver(variables_to_restore)
 
with tf.Session() as sess:
  # Restore variables from disk.
  restorer.restore(sess, "/tmp/model.ckpt")
  print("Model restored.")

#為模型添加前綴
假設(shè)我們定義的網(wǎng)絡(luò)變量是conv1/weights,而從VGG加載的變量名為vgg16/conv1/weights格侯,正常load肯定會報錯(找不到變量名),但是可以這樣:
def name_in_checkpoint(var):
  return 'vgg16/' + var.op.name
 
variables_to_restore = slim.get_model_variables()
variables_to_restore = {name_in_checkpoint(var):var for var in variables_to_restore}
restorer = tf.train.Saver(variables_to_restore)
 
with tf.Session() as sess:
  # Restore variables from disk.
  restorer.restore(sess, "/tmp/model.ckpt")
訓練模型

在該例中财著,slim.learning.train根據(jù)train_op計算損失联四、應(yīng)用梯度step。logdir指定了checkpoints和event文件的存儲路徑撑教。我們可以限制梯度step到任何數(shù)值朝墩。這里我們采用1000步。最后伟姐,save_summaries_secs=300表示每5分鐘計算一次summaries收苏,save_interval_secs=600表示每10分鐘保存一次模型的checkpoint。

g = tf.Graph()
 
# Create the model and specify the losses...
...
 
total_loss = slim.losses.get_total_loss()
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
 
# create_train_op ensures that each time we ask for the loss, the update_ops
# are run and the gradients being computed are applied too.
train_op = slim.learning.create_train_op(total_loss, optimizer)
logdir = ... # Where checkpoints are stored.
 
slim.learning.train(
    train_op,
    logdir,
    number_of_steps=1000,
    save_summaries_secs=300,
    save_interval_secs=600)
Fine-Tuning a Model on a different task

假設(shè)我們有一個已經(jīng)預訓練好的VGG16的模型愤兵。這個模型是在擁有1000分類的ImageNet數(shù)據(jù)集上進行訓練的鹿霸。但是,現(xiàn)在我們想把它應(yīng)用在只具有20個分類的Pascal VOC數(shù)據(jù)集上秆乳。為了能這樣做懦鼠,我們可以通過利用除最后一些全連接層的其他預訓練模型值來初始化新模型的達到目的:

# Load the Pascal VOC data
image, label = MyPascalVocDataLoader(...)
images, labels = tf.train.batch([image, label], batch_size=32)
 
# Create the model
predictions = vgg.vgg_16(images)
 
train_op = slim.learning.create_train_op(...)
 
# Specify where the Model, trained on ImageNet, was saved.
model_path = '/path/to/pre_trained_on_imagenet.checkpoint'
metric_ops.py
# Specify where the new model will live:
log_dir = 
 
from_checkpoint_
 
'/path/to/my_pascal_model_dir/'
 
# Restore only the convolutional layers:
variables_to_restore = slim.get_variables_to_restore(exclude=['fc6', 'fc7', 'fc8'])
init_fn = assign_from_checkpoint_fn(model_path, variables_to_restore)
 
# Start training.
slim.learning.train(train_op, log_dir, init_fn=init_fn)
evaluation loop
import tensorflow as tf

slim = tf.contrib.slim

# Load the data
images, labels = load_data(...)

# Define the network
predictions = MyModel(images)

# Choose the metrics to compute:
names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({
    'accuracy': slim.metrics.accuracy(predictions, labels),
    'precision': slim.metrics.precision(predictions, labels),
    'recall': slim.metrics.recall(mean_relative_errors, 0.3),
})

# Create the summary ops such that they also print out to std output:
summary_ops = []
for metric_name, metric_value in names_to_values.iteritems():
  op = tf.summary.scalar(metric_name, metric_value)
  op = tf.Print(op, [metric_value], metric_name)
  summary_ops.append(op)

num_examples = 10000
batch_size = 32
num_batches = math.ceil(num_examples / float(batch_size))

# Setup the global step.
slim.get_or_create_global_step()

output_dir = ... # Where the summaries are stored.
eval_interval_secs = ... # How often to run the evaluation.
slim.evaluation.evaluation_loop(
    'local',
    checkpoint_dir,
    log_dir,
    num_evals=num_batches,
    eval_op=names_to_updates.values(),
    summary_op=tf.summary.merge(summary_ops),
    eval_interval_secs=eval_interval_secs)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末钻哩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子肛冶,更是在濱河造成了極大的恐慌街氢,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件睦袖,死亡現(xiàn)場離奇詭異珊肃,居然都是意外死亡,警方通過查閱死者的電腦和手機馅笙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門伦乔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人延蟹,你說我怎么就攤上這事评矩。” “怎么了阱飘?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長虱颗。 經(jīng)常有香客問我沥匈,道長,這世上最難降的妖魔是什么忘渔? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任高帖,我火速辦了婚禮,結(jié)果婚禮上畦粮,老公的妹妹穿的比我還像新娘散址。我一直安慰自己,他們只是感情好宣赔,可當我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布预麸。 她就那樣靜靜地躺著,像睡著了一般儒将。 火紅的嫁衣襯著肌膚如雪吏祸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天钩蚊,我揣著相機與錄音贡翘,去河邊找鬼。 笑死砰逻,一個胖子當著我的面吹牛鸣驱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蝠咆,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼踊东,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起递胧,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤碑韵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后缎脾,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體祝闻,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年遗菠,在試婚紗的時候發(fā)現(xiàn)自己被綠了联喘。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡辙纬,死狀恐怖豁遭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贺拣,我是刑警寧澤蓖谢,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站譬涡,受9級特大地震影響闪幽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜涡匀,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一盯腌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧陨瘩,春花似錦腕够、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蒿囤,卻和暖如春客们,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背材诽。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工底挫, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人脸侥。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓建邓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親睁枕。 傳聞我的和親對象是個殘疾皇子官边,可洞房花燭夜當晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容

  • TensorFlow-Slim TF-Slim 是一個用于定義沸手、訓練、和評估復雜模型的TensorFlow高級庫注簿。...
    fade2black閱讀 4,202評論 1 4
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,100評論 1 32
  • 在第一次的畫思維導圖的基礎(chǔ)上對框架整體的結(jié)果有了一點點經(jīng)驗契吉,我在探索中慢慢找到感覺,繼續(xù)實踐诡渴,這本書的內(nèi)容值得推薦
    語淳珺兒閱讀 172評論 1 1