교육 후 모델을 저장/복원하는 방법
Tensorflow에서 모델을 교육한 후:
- 교육받은 모델을 저장하려면 어떻게 해야 합니까?
- 이 저장된 모델을 나중에 복원하려면 어떻게 해야 합니까?
모델 저장 및 복원에 대한 자세한 내용을 추가하기 위해 답변을 개선하고 있습니다.
인(및 그 후)Tensorflow 버전 0.11:
모델을 저장합니다.
import tensorflow as tf
#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}
#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#Create a saver object which will save all the variables
saver = tf.train.Saver()
#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1
#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)
모델 복원:
import tensorflow as tf
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
# Access saved Variables directly
print(sess.run('bias:0'))
# This will print 2, which is the value of bias that we saved
# Now, let's access and create placeholders variables and
# create feed-dict to feed new data
graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}
#Now, access the op that you want to run.
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated
이 사용 사례와 몇 가지 고급 사용 사례에 대해 자세히 설명했습니다.
Tensorflow 모델을 저장하고 복원하기 위한 빠른 전체 튜토리얼
및 그 후) 0.11의.0 Tensor Flow 전 0 0.11.0RC1에 직접 를 걸어 및 할 수 .tf.train.export_meta_graph
★★★★★★★★★★★★★★★★★」tf.train.import_meta_graph
https://www.tensorflow.org/programmers_guide/meta_graph에 따르면.
모델 저장
w1 = tf.Variable(tf.truncated_normal(shape=[10]), name='w1')
w2 = tf.Variable(tf.truncated_normal(shape=[20]), name='w2')
tf.add_to_collection('vars', w1)
tf.add_to_collection('vars', w2)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver.save(sess, 'my-model')
# `save` method will call `export_meta_graph` implicitly.
# you will get saved graph files:my-model.meta
모델 복원
sess = tf.Session()
new_saver = tf.train.import_meta_graph('my-model.meta')
new_saver.restore(sess, tf.train.latest_checkpoint('./'))
all_vars = tf.get_collection('vars')
for v in all_vars:
v_ = sess.run(v)
print(v_)
Tensorflow 2 문서
체크포인트 저장
문서에서 개작성
# -------------------------
# ----- Toy Context -----
# -------------------------
import tensorflow as tf
class Net(tf.keras.Model):
"""A simple linear model."""
def __init__(self):
super(Net, self).__init__()
self.l1 = tf.keras.layers.Dense(5)
def call(self, x):
return self.l1(x)
def toy_dataset():
inputs = tf.range(10.0)[:, None]
labels = inputs * 5.0 + tf.range(5.0)[None, :]
return (
tf.data.Dataset.from_tensor_slices(dict(x=inputs, y=labels)).repeat().batch(2)
)
def train_step(net, example, optimizer):
"""Trains `net` on `example` using `optimizer`."""
with tf.GradientTape() as tape:
output = net(example["x"])
loss = tf.reduce_mean(tf.abs(output - example["y"]))
variables = net.trainable_variables
gradients = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(gradients, variables))
return loss
# ----------------------------
# ----- Create Objects -----
# ----------------------------
net = Net()
opt = tf.keras.optimizers.Adam(0.1)
dataset = toy_dataset()
iterator = iter(dataset)
ckpt = tf.train.Checkpoint(
step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
)
manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
# ----------------------------
# ----- Train and Save -----
# ----------------------------
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
print("Restored from {}".format(manager.latest_checkpoint))
else:
print("Initializing from scratch.")
for _ in range(50):
example = next(iterator)
loss = train_step(net, example, opt)
ckpt.step.assign_add(1)
if int(ckpt.step) % 10 == 0:
save_path = manager.save()
print("Saved checkpoint for step {}: {}".format(int(ckpt.step), save_path))
print("loss {:1.2f}".format(loss.numpy()))
# ---------------------
# ----- Restore -----
# ---------------------
# In another script, re-initialize objects
opt = tf.keras.optimizers.Adam(0.1)
net = Net()
dataset = toy_dataset()
iterator = iter(dataset)
ckpt = tf.train.Checkpoint(
step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
)
manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
# Re-use the manager code above ^
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
print("Restored from {}".format(manager.latest_checkpoint))
else:
print("Initializing from scratch.")
for _ in range(50):
example = next(iterator)
# Continue training or evaluate etc.
기타 링크
keras
모델 저장 상세 가이드 -> https://www.tensorflow.org/guide/keras/save_and_serialize
체크포인트는 모든 파라미터의 정확한 값(tf)을 캡처합니다.모델에 의해 사용되는 변수 객체).체크포인트에는 모델에 의해 정의된 계산에 대한 설명이 포함되어 있지 않으므로 일반적으로 저장된 파라미터 값을 사용하는 소스 코드를 사용할 수 있는 경우에만 유용합니다.
한편 Saved Model 형식에는 파라미터 값(체크포인트)과 더불어 모델에 의해 정의된 계산에 대한 시리얼화된 설명이 포함됩니다.이 형식의 모델은 모델을 생성한 소스 코드와 독립적입니다.따라서 TensorFlowServing, TensorFlow Lite, TensorFlow.js 또는 다른 프로그래밍 언어(C, C++, Java, Go, Rust, C# 등)의 프로그램을 통해 배치하기에 적합합니다.TensorFlow API).
(하이라이트는 나만의 것)
텐서플로우 < 2
문서에서:
절약하다
# Create some variables.
v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)
inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)
# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
inc_v1.op.run()
dec_v2.op.run()
# Save the variables to disk.
save_path = saver.save(sess, "/tmp/model.ckpt")
print("Model saved in path: %s" % save_path)
복원
tf.reset_default_graph()
# Create some variables.
v1 = tf.get_variable("v1", shape=[3])
v2 = tf.get_variable("v2", shape=[5])
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, "/tmp/model.ckpt")
print("Model restored.")
# Check the values of the variables
print("v1 : %s" % v1.eval())
print("v2 : %s" % v2.eval())
simple_save
많은 좋은 답변입니다.완전성을 위해 2센트를 추가합니다: simple_save.또, 를 사용한 스탠드아론 코드의 예도 나타냅니다.tf.data.Dataset
API.API.
Python 3; Tensorflow 1.14
import tensorflow as tf
from tensorflow.saved_model import tag_constants
with tf.Graph().as_default():
with tf.Session() as sess:
...
# Saving
inputs = {
"batch_size_placeholder": batch_size_placeholder,
"features_placeholder": features_placeholder,
"labels_placeholder": labels_placeholder,
}
outputs = {"prediction": model_output}
tf.saved_model.simple_save(
sess, 'path/to/your/location/', inputs, outputs
)
복원:
graph = tf.Graph()
with restored_graph.as_default():
with tf.Session() as sess:
tf.saved_model.loader.load(
sess,
[tag_constants.SERVING],
'path/to/your/location/',
)
batch_size_placeholder = graph.get_tensor_by_name('batch_size_placeholder:0')
features_placeholder = graph.get_tensor_by_name('features_placeholder:0')
labels_placeholder = graph.get_tensor_by_name('labels_placeholder:0')
prediction = restored_graph.get_tensor_by_name('dense/BiasAdd:0')
sess.run(prediction, feed_dict={
batch_size_placeholder: some_value,
features_placeholder: some_other_value,
labels_placeholder: another_value
})
스탠드아론의 예
다음 코드는 데모를 위해 랜덤 데이터를 생성합니다.
- 플레이스 홀더를 작성하는 것부터 시작합니다.이치노「」, 「」를 합니다.
Dataset
에 그음음 and and andIterator
한 텐서,즉 텐서(텐서)를 수 있습니다input_tensor
우리 모델에 입력이 될 것입니다. - 는 ★★★★★★★★★★★★★★★★★★★★★★★★★
input_tensor
GRU 'RNN' 'RNN' 'RNN'냐면면 돼돼? - 는 실실이다
softmax_cross_entropy_with_logits
되어 있습니다.Adam
」모델은 로tf.saved_model.simple_save
를 그대로 이 "이러다"라는에 저장됩니다simple/
를 참조해 주세요. - 새 그래프에서는 .
tf.saved_model.loader.load
은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★graph.get_tensor_by_name
및Iterator
, 「」에 의한graph.get_operation_by_name
. - 마지막으로 데이터 집합의 두 배치에 대해 추론을 실행하고 저장된 모델과 복원된 모델이 모두 동일한 값을 산출하는지 확인합니다.그래, 그렇지!
코드:
import os
import shutil
import numpy as np
import tensorflow as tf
from tensorflow.python.saved_model import tag_constants
def model(graph, input_tensor):
"""Create the model which consists of
a bidirectional rnn (GRU(10)) followed by a dense classifier
Args:
graph (tf.Graph): Tensors' graph
input_tensor (tf.Tensor): Tensor fed as input to the model
Returns:
tf.Tensor: the model's output layer Tensor
"""
cell = tf.nn.rnn_cell.GRUCell(10)
with graph.as_default():
((fw_outputs, bw_outputs), (fw_state, bw_state)) = tf.nn.bidirectional_dynamic_rnn(
cell_fw=cell,
cell_bw=cell,
inputs=input_tensor,
sequence_length=[10] * 32,
dtype=tf.float32,
swap_memory=True,
scope=None)
outputs = tf.concat((fw_outputs, bw_outputs), 2)
mean = tf.reduce_mean(outputs, axis=1)
dense = tf.layers.dense(mean, 5, activation=None)
return dense
def get_opt_op(graph, logits, labels_tensor):
"""Create optimization operation from model's logits and labels
Args:
graph (tf.Graph): Tensors' graph
logits (tf.Tensor): The model's output without activation
labels_tensor (tf.Tensor): Target labels
Returns:
tf.Operation: the operation performing a stem of Adam optimizer
"""
with graph.as_default():
with tf.variable_scope('loss'):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels_tensor, name='xent'),
name="mean-xent"
)
with tf.variable_scope('optimizer'):
opt_op = tf.train.AdamOptimizer(1e-2).minimize(loss)
return opt_op
if __name__ == '__main__':
# Set random seed for reproducibility
# and create synthetic data
np.random.seed(0)
features = np.random.randn(64, 10, 30)
labels = np.eye(5)[np.random.randint(0, 5, (64,))]
graph1 = tf.Graph()
with graph1.as_default():
# Random seed for reproducibility
tf.set_random_seed(0)
# Placeholders
batch_size_ph = tf.placeholder(tf.int64, name='batch_size_ph')
features_data_ph = tf.placeholder(tf.float32, [None, None, 30], 'features_data_ph')
labels_data_ph = tf.placeholder(tf.int32, [None, 5], 'labels_data_ph')
# Dataset
dataset = tf.data.Dataset.from_tensor_slices((features_data_ph, labels_data_ph))
dataset = dataset.batch(batch_size_ph)
iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes)
dataset_init_op = iterator.make_initializer(dataset, name='dataset_init')
input_tensor, labels_tensor = iterator.get_next()
# Model
logits = model(graph1, input_tensor)
# Optimization
opt_op = get_opt_op(graph1, logits, labels_tensor)
with tf.Session(graph=graph1) as sess:
# Initialize variables
tf.global_variables_initializer().run(session=sess)
for epoch in range(3):
batch = 0
# Initialize dataset (could feed epochs in Dataset.repeat(epochs))
sess.run(
dataset_init_op,
feed_dict={
features_data_ph: features,
labels_data_ph: labels,
batch_size_ph: 32
})
values = []
while True:
try:
if epoch < 2:
# Training
_, value = sess.run([opt_op, logits])
print('Epoch {}, batch {} | Sample value: {}'.format(epoch, batch, value[0]))
batch += 1
else:
# Final inference
values.append(sess.run(logits))
print('Epoch {}, batch {} | Final inference | Sample value: {}'.format(epoch, batch, values[-1][0]))
batch += 1
except tf.errors.OutOfRangeError:
break
# Save model state
print('\nSaving...')
cwd = os.getcwd()
path = os.path.join(cwd, 'simple')
shutil.rmtree(path, ignore_errors=True)
inputs_dict = {
"batch_size_ph": batch_size_ph,
"features_data_ph": features_data_ph,
"labels_data_ph": labels_data_ph
}
outputs_dict = {
"logits": logits
}
tf.saved_model.simple_save(
sess, path, inputs_dict, outputs_dict
)
print('Ok')
# Restoring
graph2 = tf.Graph()
with graph2.as_default():
with tf.Session(graph=graph2) as sess:
# Restore saved values
print('\nRestoring...')
tf.saved_model.loader.load(
sess,
[tag_constants.SERVING],
path
)
print('Ok')
# Get restored placeholders
labels_data_ph = graph2.get_tensor_by_name('labels_data_ph:0')
features_data_ph = graph2.get_tensor_by_name('features_data_ph:0')
batch_size_ph = graph2.get_tensor_by_name('batch_size_ph:0')
# Get restored model output
restored_logits = graph2.get_tensor_by_name('dense/BiasAdd:0')
# Get dataset initializing operation
dataset_init_op = graph2.get_operation_by_name('dataset_init')
# Initialize restored dataset
sess.run(
dataset_init_op,
feed_dict={
features_data_ph: features,
labels_data_ph: labels,
batch_size_ph: 32
}
)
# Compute inference for both batches in dataset
restored_values = []
for i in range(2):
restored_values.append(sess.run(restored_logits))
print('Restored values: ', restored_values[i][0])
# Check if original inference and restored inference are equal
valid = all((v == rv).all() for v, rv in zip(values, restored_values))
print('\nInferences match: ', valid)
인쇄:
$ python3 save_and_restore.py
Epoch 0, batch 0 | Sample value: [-0.13851789 -0.3087595 0.12804556 0.20013677 -0.08229901]
Epoch 0, batch 1 | Sample value: [-0.00555491 -0.04339041 -0.05111827 -0.2480045 -0.00107776]
Epoch 1, batch 0 | Sample value: [-0.19321944 -0.2104792 -0.00602257 0.07465433 0.11674127]
Epoch 1, batch 1 | Sample value: [-0.05275984 0.05981954 -0.15913513 -0.3244143 0.10673307]
Epoch 2, batch 0 | Final inference | Sample value: [-0.26331693 -0.13013336 -0.12553 -0.04276478 0.2933622 ]
Epoch 2, batch 1 | Final inference | Sample value: [-0.07730117 0.11119192 -0.20817074 -0.35660955 0.16990358]
Saving...
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: b'/some/path/simple/saved_model.pb'
Ok
Restoring...
INFO:tensorflow:Restoring parameters from b'/some/path/simple/variables/variables'
Ok
Restored values: [-0.26331693 -0.13013336 -0.12553 -0.04276478 0.2933622 ]
Restored values: [-0.07730117 0.11119192 -0.20817074 -0.35660955 0.16990358]
Inferences match: True
TensorFlow 버전 < 0.11.0의 경우RC1:
저장된 체크포인트에는 다음 값이 포함됩니다.Variable
모델/그래프 자체가 아니라 모델에 s가 포함되어 있습니다.즉, 체크포인트를 복원할 때 그래프가 같아야 합니다.
다음은 가변 체크포인트를 저장하는 트레이닝 루프와 이전 실행에서 저장된 변수를 복원하고 예측을 계산하는 평가 섹션이 있는 선형 회귀 분석의 예입니다.물론 원하는 경우 변수를 복원하고 훈련을 계속할 수도 있습니다.
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
w = tf.Variable(tf.zeros([1, 1], dtype=tf.float32))
b = tf.Variable(tf.ones([1, 1], dtype=tf.float32))
y_hat = tf.add(b, tf.matmul(x, w))
...more setup for optimization and what not...
saver = tf.train.Saver() # defaults to saving all variables - in this case w and b
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
if FLAGS.train:
for i in xrange(FLAGS.training_steps):
...training loop...
if (i + 1) % FLAGS.checkpoint_steps == 0:
saver.save(sess, FLAGS.checkpoint_dir + 'model.ckpt',
global_step=i+1)
else:
# Here's where you're restoring the variables w and b.
# Note that the graph is exactly as it was when the variables were
# saved in a prior training run.
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
...no checkpoint found...
# Now you can run the model to get predictions
batch_x = ...load some data...
predictions = sess.run(y_hat, feed_dict={x: batch_x})
여기 의 자료가 있습니다.Variable
저장 및 복원에 대해 설명합니다.그리고 여기 이 문서들이 있습니다Saver
.
내 환경: Python 3.6, Tensorflow 1.3.0
이 있었지만, 은 금금 on on on on on on, on though though though though though though though though though though though though though though though though though though though though though though though though though though though though 에 근거하고 있다.tf.train.Saver
할 .를 했을 때.ckpt
에 의해 Saver
하거나 Tensorflow "tensorflow" "tensorflow" "tensorflow" "tensorflow" "tensorflow" "tensorflow" "tensorflow"tensorflow" "tensorflow" 하고 기억된 이름을 사용해야 'placehold_0:0'
,'dense/Adam/Weight:0'
기기사사 . . . use . . . . . . . . . . . .를 사용하는 것을 추천합니다.tf.saved_model
TensorFlow 모델 제공에서 자세한 내용은 다음과 같은 간단한 예를 참조하십시오.
모델을 저장합니다.
import tensorflow as tf
# define the tensorflow network and do some trains
x = tf.placeholder("float", name="x")
w = tf.Variable(2.0, name="w")
b = tf.Variable(0.0, name="bias")
h = tf.multiply(x, w)
y = tf.add(h, b, name="y")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# save the model
export_path = './savedmodel'
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_y = tf.saved_model.utils.build_tensor_info(y)
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs={'x_input': tensor_info_x},
outputs={'y_output': tensor_info_y},
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))
builder.add_meta_graph_and_variables(
sess, [tf.saved_model.tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
prediction_signature
},
)
builder.save()
모델을 로드합니다.
import tensorflow as tf
sess=tf.Session()
signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
input_key = 'x_input'
output_key = 'y_output'
export_path = './savedmodel'
meta_graph_def = tf.saved_model.loader.load(
sess,
[tf.saved_model.tag_constants.SERVING],
export_path)
signature = meta_graph_def.signature_def
x_tensor_name = signature[signature_key].inputs[input_key].name
y_tensor_name = signature[signature_key].outputs[output_key].name
x = sess.graph.get_tensor_by_name(x_tensor_name)
y = sess.graph.get_tensor_by_name(y_tensor_name)
y_out = sess.run(y, {x: 3.0})
모델 정의에서는 델 에 델 는 의 분 지 으 이 있 부 there are,, by며가ition the parts to model defin두 the모정 two모의,?Supervisor
as ~하듯이graph.pbtxt
델 렉 디ors모 directory and토 like텐리체다 in같값저크에파포은장일인과트됩다니point서 files, into tens values숫음에자의서와 ofmodel.ckpt-1003418
.
The model definition can be restored using 모델 정의는 다음을 사용하여 복원할 수 있습니다.tf.import_graph_def
, , and the weights are restored using 중량은 다음 명령을 사용하여 복원됩니다.Saver
.
하지만, 지?Saver
모델 그래프에 부착된 변수 목록을 사용하여 이 컬렉션에 연결된 변수 목록을 사용하여 초기화되지 않으므로 이 수집은 초기화할 수 없습니다.에서는 Graph 모델에 연결된 변수의 특수 컬렉션 보유 목록을 사용하고 있으며 이 컬렉션은 import_graph_def를 사용하여 초기화되지 않았기 때문에 현재 이 두 가지를 함께 사용할 수 없습니다(수정 로드맵에 나와 있습니다). Ryan 의해, 그래프를 수동으로 작성해, 「Ryan Sepassi」를 사용해 .- 「 Ryan Sepassi 」를 사용해 .Saver
츠키노
(을를할 수도 .import_graph_def
수동 및 " " " "tf.add_to_collection(tf.GraphKeys.VARIABLES, variable)
, 「」를 사용합니다.Saver
)
당신은 또한 이 쉬운 방법을 택할 수 있습니다.
1단계: 모든 변수 초기화
W1 = tf.Variable(tf.truncated_normal([6, 6, 1, K], stddev=0.1), name="W1")
B1 = tf.Variable(tf.constant(0.1, tf.float32, [K]), name="B1")
Similarly, W2, B2, W3, .....
2: 모델2: " " " " " " "Saver
model_saver = tf.train.Saver()
# Train the model and save it in the end
model_saver.save(session, "saved_models/CNN_New.ckpt")
3단계: 모델 복원
with tf.Session(graph=graph_cnn) as session:
model_saver.restore(session, "saved_models/CNN_New.ckpt")
print("Model restored.")
print('Initialized')
4단계: 변수 확인
W1 = session.run(W1)
print(W1)
다른 python 인스턴스에서 실행하는 동안
with tf.Session() as sess:
# Restore latest checkpoint
saver.restore(sess, tf.train.latest_checkpoint('saved_model/.'))
# Initalize the variables
sess.run(tf.global_variables_initializer())
# Get default graph (supply your custom graph if you have one)
graph = tf.get_default_graph()
# It will give tensor object
W1 = graph.get_tensor_by_name('W1:0')
# To get the value (numpy array)
W1_value = session.run(W1)
의 를 및 tf.train.Saver
최적의 옵션입니다.
... # build your model
saver = tf.train.Saver()
with tf.Session() as sess:
... # train the model
saver.save(sess, "/tmp/my_great_model")
with tf.Session() as sess:
saver.restore(sess, "/tmp/my_great_model")
... # use the model
그래프 구조 자체를 저장/복원할 수도 있습니다(자세한 내용은 MetaGraph 설명서 참조).디폴트로는Saver
를 .meta
전화하시면 .import_meta_graph()
하고 그래프 구조를 반환한다.Saver
모델 상태를 복원하는 데 사용할 수 있습니다.
saver = tf.train.import_meta_graph("/tmp/my_great_model.meta")
with tf.Session() as sess:
saver.restore(sess, "/tmp/my_great_model")
... # use the model
하지만, 훨씬 더 빠른 것이 필요한 경우가 있습니다.예를 들어 조기 중지를 구현한 경우 검증 세트에서 측정된 대로 교육 중에 모델이 개선될 때마다 체크포인트를 저장한 다음 한동안 진행이 없으면 최적의 모델로 롤백하려고 합니다.개선될 때마다 모델을 디스크에 저장하면 교육 속도가 크게 느려집니다.요령은 변수 상태를 메모리에 저장한 후 나중에 복원하는 것입니다.
... # build your model
# get a handle on the graph nodes we need to save/restore the model
graph = tf.get_default_graph()
gvars = graph.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
assign_ops = [graph.get_operation_by_name(v.op.name + "/Assign") for v in gvars]
init_values = [assign_op.inputs[1] for assign_op in assign_ops]
with tf.Session() as sess:
... # train the model
# when needed, save the model state to memory
gvars_state = sess.run(gvars)
# when needed, restore the model state
feed_dict = {init_value: val
for init_value, val in zip(init_values, gvars_state)}
sess.run(assign_ops, feed_dict=feed_dict)
시: 변수 생성 시X
연산 TensorFlow를 X/Assign
이치노플레이스 홀더나 추가 할당 작업(그래프만 복잡해짐)을 작성하는 대신 이러한 기존 할당 작업만 사용합니다.첫하고 두 입력 「 」 )입니다.assign_op.inputs[1]
을 사용하다) 하려면 (아닌) 을 해야 .feed_dict
초기값을 바꿉니다. Tensor 뿐만 아니라 op에 수 Tensor Flow는 합니다.
Yaroslav가 말했듯이 그래프를 Import하고 변수를 수동으로 작성한 후 Saver를 사용하여 graph_def 및 체크포인트에서 복원을 해킹할 수 있습니다.
개인적인 용도로 구현했기 때문에 여기서 코드를 공유하려고 합니다.
링크: https://gist.github.com/nikitakit/6ef3b72be67b86cb7868
(물론 이것은 해킹이며, 이렇게 저장된 모델이 TensorFlow의 향후 버전에서 읽을 수 있는 상태로 유지된다는 보장은 없습니다.)
내부적으로 저장된 모델인 경우 모든 변수의 restoreer를 다음과 같이 지정하기만 하면 됩니다.
restorer = tf.train.Saver(tf.all_variables())
현재 세션에서 변수를 복원하기 위해 사용합니다.
restorer.restore(self._sess, model_file)
외부 모델의 경우 변수 이름에서 변수 이름으로의 매핑을 지정해야 합니다.다음 명령을 사용하여 모델 변수 이름을 볼 수 있습니다.
python /path/to/tensorflow/tensorflow/python/tools/inspect_checkpoint.py --file_name=/path/to/pretrained_model/model.ckpt
inspect_checkpoint.py 스크립트는 Tensorflow 소스의 '.tensorflow/python/tools' 폴더에 있습니다.
매핑을 지정하려면 클래스 및 스크립트 세트가 포함된 Tensorflow-Worklab을 사용하여 여러 모델을 교육 및 재교육할 수 있습니다.여기에서는 ResNet 모델을 재교육하는 예를 보여 줍니다.
다음은 파일에서 그래프를 로드할지 런타임 중에 빌드할지 여부에 대한 두 가지 기본 사례에 대한 간단한 솔루션입니다.
이 답은 Tensorflow 0.12+(1.0 포함)에 적용됩니다.
코드로 그래프 재구성
저장
graph = ... # build the graph
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.save(sess, 'my-model')
싣고 있는
graph = ... # build the graph
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.restore(sess, tf.train.latest_checkpoint('./'))
# now you can use the graph, continue training or whatever
파일에서 그래프도 로드하는 중
이 기술을 사용할 때는 모든 레이어/변수가 고유한 이름을 명시적으로 설정해야 합니다.그렇지 않으면 Tensorflow는 이름 자체를 고유하게 만들고 파일에 저장된 이름과 다릅니다.이전 기술에서는 문제가 되지 않습니다.로드와 저장 모두에서 이름이 동일하게 "혼합"되어 있기 때문입니다.
저장
graph = ... # build the graph
for op in [ ... ]: # operators you want to use after restoring the model
tf.add_to_collection('ops_to_restore', op)
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.save(sess, 'my-model')
싣고 있는
with ... as sess: # your session object
saver = tf.train.import_meta_graph('my-model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
ops = tf.get_collection('ops_to_restore') # here are your operators in the same order in which you saved them to the collection
을 tf.keras로 합니다.TF2.0
TF1. TF1.x의 저장에 몇 를 더 . 저장에 대한 몇 가지 포인터를 더 제공하고 싶습니다.tensorflow.keras
모델을 저장하는 방법은 여러 가지가 있기 때문에 조금 복잡한 모델입니다.
에서는 예를 '', '살리다', '살리다', ''tensorflow.keras
로 삼다model_path
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★이것은, 최신의 텐서 플로우(TF2.0)에서 유효하게 동작합니다.가까운 시일 내에 변경사항이 있으면 이 설명을 갱신하겠습니다.
전체 모델 저장 및 로드
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
#import data
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# create a model
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
# compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# Create a basic model instance
model=create_model()
model.fit(x_train, y_train, epochs=1)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save entire model to a HDF5 file
model.save('./model_path/my_model.h5')
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('./model_path/my_model.h5')
loss, acc = new_model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
모델 저장 및 로드 무게만
모형 가중치만 저장한 다음 가중치를 로드하여 모형을 복원하려는 경우
model.fit(x_train, y_train, epochs=5)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save the weights
model.save_weights('./checkpoints/my_checkpoint')
# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
keras 체크포인트콜백을 사용한 저장 및 복원
# include the epoch in the file name. (uses `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
checkpoint_path, verbose=1, save_weights_only=True,
# Save weights, every 5-epochs.
period=5)
model = create_model()
model.save_weights(checkpoint_path.format(epoch=0))
model.fit(train_images, train_labels,
epochs = 50, callbacks = [cp_callback],
validation_data = (test_images,test_labels),
verbose=0)
latest = tf.train.latest_checkpoint(checkpoint_dir)
new_model = create_model()
new_model.load_weights(latest)
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
사용자 지정 메트릭을 사용하여 모델 저장
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Custom Loss1 (for example)
@tf.function()
def customLoss1(yTrue,yPred):
return tf.reduce_mean(yTrue-yPred)
# Custom Loss2 (for example)
@tf.function()
def customLoss2(yTrue, yPred):
return tf.reduce_mean(tf.square(tf.subtract(yTrue,yPred)))
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy', customLoss1, customLoss2])
return model
# Create a basic model instance
model=create_model()
# Fit and evaluate model
model.fit(x_train, y_train, epochs=1)
loss, acc,loss1, loss2 = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
model.save("./model.h5")
new_model=tf.keras.models.load_model("./model.h5",custom_objects={'customLoss1':customLoss1,'customLoss2':customLoss2})
커스텀 ops를 사용한 keras 모델 저장
(「」 「ops」).tf.tile
람다를 좋아하다그렇지 않으면 모델을 저장할 수 없습니다.
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras import Model
def my_fun(a):
out = tf.tile(a, (1, tf.shape(a)[0]))
return out
a = Input(shape=(10,))
#out = tf.tile(a, (1, tf.shape(a)[0]))
out = Lambda(lambda x : my_fun(x))(a)
model = Model(a, out)
x = np.zeros((50,10), dtype=np.float32)
print(model(x).numpy())
model.save('my_model.h5')
#load the model
new_model=tf.keras.models.load_model("my_model.h5")
tf.keras 모델을 저장하는 다양한 방법 중 몇 가지에 대해 설명했습니다.하지만, 다른 많은 방법들이 있다.위에서 다루지 않은 사용 사례가 있는 경우 아래 의견을 제시해 주십시오.감사합니다!
TensorFlow/skflow의 예도 확인할 수 있습니다. TensorFlow/skflow는 다음을 제공합니다.save
★★★★★★★★★★★★★★★★★」restore
모델을 쉽게 관리할 수 있는 방법을 제공합니다.모델 백업 빈도도 제어할 수 있는 매개 변수가 있습니다.
tf.train을 사용하면.Monitored Training Session은 기본 세션으로 저장/복원하기 위해 코드를 추가할 필요가 없습니다.Monitored Training Session의 컨스트럭터에 체크포인트 dir 이름을 전달하기만 하면 세션 후크를 사용하여 이러한 작업을 처리할 수 있습니다.
여기 있는 모든 답변은 훌륭하지만, 저는 두 가지를 덧붙이고 싶습니다.
우선, @user7505159 의 회답에 대해 자세히 설명하려면 , restore 하고 있는 파일명의 선두에 「.」를 추가하는 것이 중요합니다.
예를 들어, 다음과 같이 파일 이름에 "./"가 없는 그래프를 저장할 수 있습니다.
# Some graph defined up here with specific names
saver = tf.train.Saver()
save_file = 'model.ckpt'
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.save(sess, save_file)
그러나 그래프를 복원하려면 file_name에 "."를 추가해야 할 수 있습니다.
# Same graph defined up here
saver = tf.train.Saver()
save_file = './' + 'model.ckpt' # String addition used for emphasis
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, save_file)
항상 "."가 필요한 것은 아니지만, 사용 환경과 TensorFlow 버전에 따라 문제가 발생할 수 있습니다.
, 이, 이, 이, 이, 이, 이, 이, 이, 이.sess.run(tf.global_variables_initializer())
는 세션을 복원하기 전에 중요할 수 있습니다.
세션을 하려고 할 때되지 않은 된 오류가 " " "를 .sess.run(tf.global_variables_initializer())
before saver.restore(sess, save_file)
두통을 덜어줄 수 있어요
버전에 "Tensorflow"는 "Tensorflow"입니다.tf.train.Checkpoint
및 하는 데 되는 방법입니다
Checkpoint.save
★★★★★★★★★★★★★★★★★」Checkpoint.restore
tf.train과 대조적으로 객체 기반 체크포인트를 쓰고 읽습니다.variable.name 기반의 체크포인트를 쓰고 읽어내는 세이버.개체 기반 체크포인트는 명명된 모서리를 가진 Python 개체(레이어, Optimizer, 변수 등) 간의 종속성 그래프를 저장합니다. 이 그래프는 체크포인트를 복원할 때 변수를 일치시키는 데 사용됩니다.Python 프로그램의 변경에 보다 강력할 수 있으며, 열심히 실행할 때 변수에 대한 Restore-on-create를 지원합니다.새 코드보다 선호합니다.
다음은 예를 제시하겠습니다.
import tensorflow as tf
import os
tf.enable_eager_execution()
checkpoint_directory = "/tmp/training_checkpoints"
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))
for _ in range(num_training_steps):
optimizer.minimize( ... ) # Variables will be restored on creation.
status.assert_consumed() # Optional sanity checks.
checkpoint.save(file_prefix=checkpoint_prefix)
6255호에서 설명한 바와 같이:
use '**./**model_name.ckpt'
saver.restore(sess,'./my_model_final.ckpt')
대신
saver.restore('my_model_final.ckpt')
텐서플로우 2.0의 경우 다음과 같이 간단합니다.
# Save the model model.save('path_to_my_model.h5')
복원 방법:
new_model = tensorflow.keras.models.load_model('path_to_my_model.h5')
텐서플로우-2.0의 경우
아주 간단합니다.
import tensorflow as tf
절약하다
model.save("model_name")
복원
model = tf.keras.models.load_model('model_name')
다음으로 Tensorflow 2.0 Saved Model 형식(도큐스에 따르면 권장 형식)을 단순한 MNIST 데이터셋 분류자로 사용하고, Keras 함수 API를 사용하는 간단한 예를 나타냅니다.
# Imports
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model
import matplotlib.pyplot as plt
# Load data
mnist = tf.keras.datasets.mnist # 28 x 28
(x_train,y_train), (x_test, y_test) = mnist.load_data()
# Normalize pixels [0,255] -> [0,1]
x_train = tf.keras.utils.normalize(x_train,axis=1)
x_test = tf.keras.utils.normalize(x_test,axis=1)
# Create model
input = Input(shape=(28,28), dtype='float64', name='graph_input')
x = Flatten()(input)
x = Dense(128, activation='relu')(x)
x = Dense(128, activation='relu')(x)
output = Dense(10, activation='softmax', name='graph_output', dtype='float64')(x)
model = Model(inputs=input, outputs=output)
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train
model.fit(x_train, y_train, epochs=3)
# Save model in SavedModel format (Tensorflow 2.0)
export_path = 'model'
tf.saved_model.save(model, export_path)
# ... possibly another python program
# Reload model
loaded_model = tf.keras.models.load_model(export_path)
# Get image sample for testing
index = 0
img = x_test[index] # I normalized the image on a previous step
# Predict using the signature definition (Tensorflow 2.0)
predict = loaded_model.signatures["serving_default"]
prediction = predict(tf.constant(img))
# Show results
print(np.argmax(prediction['graph_output'])) # prints the class number
plt.imshow(x_test[index], cmap=plt.cm.binary) # prints the image
죠?serving_default
선택한 태그의 시그니처 정의 이름입니다(이 경우 기본).serve
태그가 선택되었습니다).또한, 여기에서는 다음을 사용하여 모델의 태그와 시그니처를 찾는 방법에 대해 설명합니다.saved_model_cli
면책 사항
이것은 기본적인 예에 불과하지만, 완전한 답은 아닙니다.향후 갱신할 수 있을지도 모릅니다.를 들어 .SavedModel
TF 2.0의 경우
@Tom의 답변은 Saved Model의 예이지만 Tensorflow 2.0에서는 동작하지 않습니다.불행히도 몇 가지 변경이 있기 때문입니다.
@Vishnuvardhan Janapati의 답변에는 TF 2.0이라고 되어 있습니다만, Saved Model 포맷은 아닙니다.
네트워크 내의 변수는 다음과 같이 저장할 수 있습니다.
saver = tf.train.Saver()
saver.save(sess, 'path of save/fileName.ckpt')
나중에 또는 다른 스크립트로 재사용할 수 있도록 네트워크를 복원하려면 다음 명령을 사용합니다.
saver = tf.train.Saver()
saver.restore(sess, tf.train.latest_checkpoint('path of save/')
sess.run(....)
주의사항:
sess
첫 번째 주행과 이후 주행 사이에 동일해야 합니다(예: 구조).saver.restore
에는 개별 파일 경로가 아닌 저장된 파일의 폴더 경로가 필요합니다.
@Vishnuvardhan Janapati의 답변에 따라 TensorFlow 2.0.0에서 커스텀 레이어/메트릭/손실을 사용하여 모델을 저장하고 새로고침하는 다른 방법이 있습니다.
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras.utils.generic_utils import get_custom_objects
# custom loss (for example)
def custom_loss(y_true,y_pred):
return tf.reduce_mean(y_true - y_pred)
get_custom_objects().update({'custom_loss': custom_loss})
# custom loss (for example)
class CustomLayer(Layer):
def __init__(self, ...):
...
# define custom layer and all necessary custom operations inside custom layer
get_custom_objects().update({'CustomLayer': CustomLayer})
해 두면, 「 」로 보존할 수 있습니다.tf.keras.models.save_model
★★★★★★★★★★★★★★★★★」model.save
★★★★★★★★★★★★★★★★★」ModelCheckpoint
할 수 를 들어, 「커스텀오브젝트」라고 하는 간단한 방법이 있습니다.
new_model = tf.keras.models.load_model("./model.h5"})
Tensorflow 2.6 : 더 심플해져서 모델을 2가지 형식으로 저장할 수 있습니다.
- Saved_model(tf-serving 호환)
- H5 또는 HDF5
두 가지 형식으로 모델 저장:
from tensorflow.keras import Model
inputs = tf.keras.Input(shape=(224,224,3))
y = tf.keras.layers.Conv2D(24, 3, activation='relu', input_shape=input_shape[1:])(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(y)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.save("saved_model/my_model") #To Save in Saved_model format
model.save("my_model.h5") #To save model in H5 or HDF5 format
두 가지 형식으로 모형을 로드하는 방법
import tensorflow as tf
h5_model = tf.keras.models.load_model("my_model.h5") # loading model in h5 format
h5_model.summary()
saved_m = tf.keras.models.load_model("saved_model/my_model") #loading model in saved_model format
saved_m.summary()
tf.train.Saver
모델을 저장합니다. ""를 var_list
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★val_list
하다
tf.trainable_variables
or or or openicle.tf.global_variables
.
모델을 저장하고 싶은 곳이라면,
self.saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
...
self.saver.save(sess, filename)
것을 해 두어라.tf.Variable
나중에 이름을 사용하여 복원할 수 있기 때문에 이름이 있어야 합니다.그리고 당신이 예측하고 싶은 곳은
saver = tf.train.import_meta_graph(filename)
name = 'name given when you saved the file'
with tf.Session() as sess:
saver.restore(sess, name)
print(sess.run('W1:0')) #example to retrieve by variable name
보호기가 해당 세션 내에서 실행되는지 확인합니다. 이 경우 해 주십시오.tf.train.latest_checkpoint('./')
최신 체크 포인트만 사용됩니다.
현재 버전:
tensorflow (1.13.1)
tensorflow-gpu (1.13.1)
간단한 방법은
저장:
model.save("model.h5")
복원:
model = tf.keras.models.load_model("model.h5")
새로운 버전의 텐서플로우 2.0에서는 모델을 저장/로드하는 프로세스가 훨씬 쉬워졌습니다.TensorFlow용 고급 API인 Keras API 구현으로 인해
모델을 저장하려면:다음의 메뉴얼을 참조해 주세요.https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/models/save_model
tf.keras.models.save_model(model_name, filepath, save_format)
모델을 로드하려면:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/models/load_model
model = tf.keras.models.load_model(filepath)
가장 쉬운 방법은 모델을 저장하는 온라인과 모델을 로드하는 한 줄의 keras api를 사용하는 것입니다.
from keras.models import load_model
my_model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del my_model # deletes the existing model
my_model = load_model('my_model.h5') # returns a compiled model identical to the previous one
Tensorflow에서 saver 객체를 사용하여 학습된 모델을 저장할 수 있습니다.이 개체는 모델을 저장하고 복원하는 방법을 제공합니다.
TensorFlow에서 학습된 모델을 저장하려면:
tf.train.Saver.save(sess, save_path, global_step=None, latest_filename=None,
meta_graph_suffix='meta', write_meta_graph=True,
write_state=True, strip_default_attrs=False,
save_debug_info=False)
TensorFlow에서 저장된 모델을 복원하려면:
tf.train.Saver.restore(sess, save_path, latest_filename=None,
meta_graph_suffix='meta', clear_devices=False,
import_scope=None)
언급URL : https://stackoverflow.com/questions/33759623/how-to-save-restore-a-model-after-training
'sourcecode' 카테고리의 다른 글
SQL 연금술 로드 테스트: "Timeout Error:크기 3 오버플로우 0의 QueuePool 제한에 도달했으며 연결 시간 초과, 시간 초과 30" (0) | 2023.01.15 |
---|---|
PHP에서 요청 헤더를 읽는 방법 (0) | 2023.01.15 |
subprocess.call()의 출력을 취득하고 있습니다. (0) | 2023.01.10 |
Python의 'in' 연산자를 재정의하시겠습니까? (0) | 2023.01.10 |
phpMyAdmin - Error > Invalid format 파라미터? (0) | 2023.01.10 |