婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁(yè) > 知識(shí)庫(kù) > Tensorflow 如何從checkpoint文件中加載變量名和變量值

Tensorflow 如何從checkpoint文件中加載變量名和變量值

熱門(mén)標(biāo)簽:電銷(xiāo)機(jī)器人的風(fēng)險(xiǎn) 河北防封卡電銷(xiāo)卡 天津電話機(jī)器人公司 開(kāi)封語(yǔ)音外呼系統(tǒng)代理商 手機(jī)網(wǎng)頁(yè)嵌入地圖標(biāo)注位置 400電話辦理哪種 地圖標(biāo)注線上如何操作 應(yīng)電話機(jī)器人打電話違法嗎 開(kāi)封自動(dòng)外呼系統(tǒng)怎么收費(fèi)

假設(shè)你已經(jīng)經(jīng)過(guò)上千次的迭代,并且得到了以下模型:

則從這些checkpoint文件中加載變量名和變量值代碼如下:

model_dir = './ckpt-182802'
import tensorflow as tf
from tensorflow.python import pywrap_tensorflow
reader = pywrap_tensorflow.NewCheckpointReader(model_dir)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in var_to_shape_map:
     print("tensor_name: ", key)
     print(reader.get_tensor(key)) # Remove this is you want to print only variable names

Mnist

下面將給出一個(gè)基于卷積神經(jīng)網(wǎng)絡(luò)的手寫(xiě)數(shù)字識(shí)別樣例:

# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework import graph_util
log_dir = './tensorboard'
mnist = input_data.read_data_sets(train_dir="./mnist_data",one_hot=True)
if tf.gfile.Exists(log_dir):
        tf.gfile.DeleteRecursively(log_dir)
tf.gfile.MakeDirs(log_dir)

#定義輸入數(shù)據(jù)mnist圖片大小28*28*1=784,None表示batch_size
x = tf.placeholder(dtype=tf.float32,shape=[None,28*28],name="input")
#定義標(biāo)簽數(shù)據(jù),mnist共10類(lèi)
y_ = tf.placeholder(dtype=tf.float32,shape=[None,10],name="y_")
#將數(shù)據(jù)調(diào)整為二維數(shù)據(jù),w*H*c---> 28*28*1,-1表示N張
image = tf.reshape(x,shape=[-1,28,28,1])

#第一層,卷積核={5*5*1*32},池化核={2*2*1,1*2*2*1}
w1 = tf.Variable(initial_value=tf.random_normal(shape=[5,5,1,32],stddev=0.1,dtype=tf.float32,name="w1"))
b1= tf.Variable(initial_value=tf.zeros(shape=[32]))
conv1 = tf.nn.conv2d(input=image,filter=w1,strides=[1,1,1,1],padding="SAME",name="conv1")
relu1 = tf.nn.relu(tf.nn.bias_add(conv1,b1),name="relu1")
pool1 = tf.nn.max_pool(value=relu1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
#shape={None,14,14,32}
#第二層,卷積核={5*5*32*64},池化核={2*2*1,1*2*2*1}
w2 = tf.Variable(initial_value=tf.random_normal(shape=[5,5,32,64],stddev=0.1,dtype=tf.float32,name="w2"))
b2 = tf.Variable(initial_value=tf.zeros(shape=[64]))
conv2 = tf.nn.conv2d(input=pool1,filter=w2,strides=[1,1,1,1],padding="SAME")
relu2 = tf.nn.relu(tf.nn.bias_add(conv2,b2),name="relu2")
pool2 = tf.nn.max_pool(value=relu2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME",name="pool2")
#shape={None,7,7,64}
#FC1
w3 = tf.Variable(initial_value=tf.random_normal(shape=[7*7*64,1024],stddev=0.1,dtype=tf.float32,name="w3"))
b3 = tf.Variable(initial_value=tf.zeros(shape=[1024]))
#關(guān)鍵,進(jìn)行reshape
input3 = tf.reshape(pool2,shape=[-1,7*7*64],name="input3")
fc1 = tf.nn.relu(tf.nn.bias_add(value=tf.matmul(input3,w3),bias=b3),name="fc1")
#shape={None,1024}
#FC2
w4 = tf.Variable(initial_value=tf.random_normal(shape=[1024,10],stddev=0.1,dtype=tf.float32,name="w4"))
b4 = tf.Variable(initial_value=tf.zeros(shape=[10]))
fc2 = tf.nn.bias_add(value=tf.matmul(fc1,w4),bias=b4,name="logit")
#shape={None,10}
#定義交叉熵?fù)p失
# 使用softmax將NN計(jì)算輸出值表示為概率
y = tf.nn.softmax(fc2,name="out")

# 定義交叉熵?fù)p失函數(shù)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=fc2,labels=y_)
loss = tf.reduce_mean(cross_entropy)
tf.summary.scalar('Cross_Entropy',loss)
#定義solver
train = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss=loss)
for var in tf.trainable_variables():
	print var
#train = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss=loss)

#定義正確值,判斷二者下標(biāo)index是否相等
correct_predict = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
#定義如何計(jì)算準(zhǔn)確率
accuracy = tf.reduce_mean(tf.cast(correct_predict,dtype=tf.float32),name="accuracy")
tf.summary.scalar('Training_ACC',accuracy)
#定義初始化op
merged = tf.summary.merge_all()
init = tf.global_variables_initializer()
saver = tf.train.Saver()
#訓(xùn)練NN
with tf.Session() as session:
    session.run(fetches=init)
    writer = tf.summary.FileWriter(log_dir,session.graph) #定義記錄日志的位置
    for i in range(0,500):
        xs, ys = mnist.train.next_batch(100)
        session.run(fetches=train,feed_dict={x:xs,y_:ys})
        if i%10 == 0:
            train_accuracy,summary = session.run(fetches=[accuracy,merged],feed_dict={x:xs,y_:ys})
            writer.add_summary(summary,i)
            print(i,"accuracy=",train_accuracy)
    '''
    #訓(xùn)練完成后,將網(wǎng)絡(luò)中的權(quán)值轉(zhuǎn)化為常量,形成常量graph,注意:需要x與label
    constant_graph = graph_util.convert_variables_to_constants(sess=session,
                                                            input_graph_def=session.graph_def,
                                                            output_node_names=['out','y_','input'])
    #將帶權(quán)值的graph序列化,寫(xiě)成pb文件存儲(chǔ)起來(lái)
    with tf.gfile.FastGFile("lenet.pb", mode='wb') as f:
        f.write(constant_graph.SerializeToString())
    '''
    saver.save(session,'./ckpt')

補(bǔ)充:查看tensorflow產(chǎn)生的checkpoint文件內(nèi)容的方法

tensorflow在保存權(quán)重模型時(shí)多使用tf.train.Saver().save 函數(shù)進(jìn)行權(quán)重保存,保存的ckpt文件無(wú)法直接打開(kāi),但tensorflow提供了相關(guān)函數(shù) tf.train.NewCheckpointReader 可以對(duì)ckpt文件進(jìn)行權(quán)重查看。

import os
from tensorflow.python import pywrap_tensorflow

checkpoint_path = os.path.join('modelckpt', "fc_nn_model")
# Read data from checkpoint file
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map()
# Print tensor name and values
for key in var_to_shape_map:
    print("tensor_name: ", key)
    print(reader.get_tensor(key))

其中‘modelckpt'是存放.ckpt文件的文件夾,"fc_nn_model"是文件名,如下圖所示。

 

var_to_shape_map是一個(gè)字典,其中的鍵值是變量名,對(duì)應(yīng)的值是該變量的形狀,如

{‘LSTM_input/bias_LSTM/Adam_1': [128]}

想要查看某變量值時(shí),需要調(diào)用get_tensor函數(shù),即輸入以下代碼:

reader.get_tensor('LSTM_input/bias_LSTM/Adam_1')

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • 使用tensorflow 實(shí)現(xiàn)反向傳播求導(dǎo)
  • TensorFlow的自動(dòng)求導(dǎo)原理分析
  • tensorflow中的梯度求解及梯度裁剪操作
  • Python3安裝tensorflow及配置過(guò)程
  • 解決tensorflow 與keras 混用之坑
  • tensorflow中的數(shù)據(jù)類(lèi)型dtype用法說(shuō)明

標(biāo)簽:常州 駐馬店 山東 蘭州 宿遷 六盤(pán)水 成都 江蘇

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Tensorflow 如何從checkpoint文件中加載變量名和變量值》,本文關(guān)鍵詞  Tensorflow,如何,從,checkpoint,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Tensorflow 如何從checkpoint文件中加載變量名和變量值》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于Tensorflow 如何從checkpoint文件中加載變量名和變量值的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 米泉市| 禹城市| 华池县| 怀化市| 太湖县| 临潭县| 道真| 绥阳县| 阳西县| 双桥区| 霞浦县| 三台县| 临颍县| 泾阳县| 墨脱县| 杭州市| 平利县| 高密市| 晋中市| 西贡区| 永泰县| 馆陶县| 普定县| 南和县| 岳池县| 扎赉特旗| 日土县| 满洲里市| 水城县| 十堰市| 凤庆县| 静乐县| 深州市| 潜江市| 通化市| 田阳县| 拉萨市| 宣汉县| 三穗县| 常州市| 赞皇县|