Я реализовал MLP в tenorflow-gpu 1.8.0 и использую Hyperopt, чтобы найти наилучшую конфигурацию параметров.Файл контрольных точек создается каждый раз, когда функция потерь дополнительно минимизируется.Файл контрольных точек всегда перезаписывается, и в конце процесса я получаю только эти файлы:
контрольная точка
Model_1_checkpoint.ckpt.data-00000-of-00001
Model_1_checkpoint.ckpt.index
Model_1_checkpoint.meta
Ниже показан код для обучения MLP (который находится внутри функции):
# Hyperparameters
n_step= np.round(parameters['step'],3)
n_hidden= np.int(parameters['number_neurons'])
n_bias= np.round(parameters['bias'],3)
n_batch= np.int(parameters['batch'])
# General variables
N_instances= xtrain_data_1_T60.shape[0]
N_input= xtrain_data_1_T60.shape[1]
N_classes= enc_ytrain_data_1_T60.shape[1]
N_epochs= 500
display_step= 100
# Reset graph
tf.reset_default_graph()
# Placeholders
X= tf.placeholder(name= "Logs", dtype= tf.float32, shape= [None, N_input])
y= tf.placeholder(name= "Facies", dtype= tf.float32, shape= [None, N_classes])
# MLP network architecture
input_layer= tf.layers.dense(X, units= N_input, activation= None,
kernel_initializer= tf.keras.initializers.glorot_normal(1969),
bias_initializer= tf.keras.initializers.Zeros())
hidden_layer= tf.layers.dense(input_layer, units= n_hidden, activation= tf.nn.tanh,
kernel_initializer= tf.keras.initializers.he_normal(1969),
bias_initializer= tf.keras.initializers.Constant(n_bias))
output_layer= tf.layers.dense(hidden_layer, units= N_classes, activation= tf.nn.softmax,
kernel_initializer= tf.keras.initializers.he_normal(1969),
bias_initializer= tf.keras.initializers.Zeros(), name= "mlp_output")
loss_op= tf.reduce_mean(tf.keras.backend.binary_crossentropy(y, output_layer))
optimizer= tf.train.GradientDescentOptimizer(learning_rate= n_step).minimize(loss_op)
# Initialize variables
init= tf.initialize_all_variables() #tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Training loop
for epoch in range(0, N_epochs):
avg_cost = 0.
total_batch= np.int(N_instances/n_batch)
start_idx= 0
end_idx= n_batch
for i in range(0, total_batch):
batchx= xtrain_data_1_T60[start_idx:end_idx,:]
batchy= enc_ytrain_data_1_T60[start_idx:end_idx,:]
_, c= sess.run([optimizer, loss_op], feed_dict= {X: batchx, y: batchy})
avg_cost += c/total_batch
# Set next batch
start_idx += n_batch
end_idx += n_batch
if (end_idx > N_instances):
end_idx= N_instances
if (epoch % display_step == 0):
print("Epoch : %03d/%03d cost : %.4f\n"%(epoch, N_epochs, avg_cost))
print("Optimization finished\n")
prediction_1= sess.run(output_layer, feed_dict= {X: xvalidation_data_1_V40})
prediction_1= prediction_1.argmax(axis= 1) + 1
# Initialize a saver to save the current best model
saver= tf.train.Saver(max_to_keep= 1)
# Only check for prediction results with 3 lithofacies. Otherwise, I assign a dummy error and accuracy
if len(np.unique(prediction_1)) == 3:
error= 1. - metrics.recall_score(yvalidation_data_1_V40, prediction_1, average= 'micro')
accuracy= metrics.accuracy_score(yvalidation_data_1_V40, prediction_1)
global temp_error
if (error < temp_error):
temp_error= error
saver.save(sess, '{}/{}'.format(checkpoint_path, checkpoint_name))
print("Best model saved in file: ", '{}/{}'.format(checkpoint_path, checkpoint_name))
print()
else:
error= 3
accuracy= 0.00
print("Error: {}".format(error))
print("Accuracy: {:.2%}".format(accuracy))
print("Predicted number of lithofacies: {}\n".format(len(np.unique(prediction_1))))
sess.close()
Затем втем же сценарием я восстанавливаю контрольную точку сохранения для вычисления прогнозов:
tf.reset_default_graph()
# Restore the best model and predict again
with tf.Session() as sess:
new_saver= tf.train.import_meta_graph(checkpoint_path + "/" + checkpoint_name + ".meta")
new_saver.restore(sess, checkpoint_path)
# Retrieve placeholder from restored graph
X= best_model_1.get_tensor_by_name('Logs:0')
# Retrieve output layer of MLP network to compute predictions
pred= best_model_1.get_tensor_by_name('mlp_output/kernel:0')
model_prob_density_1= sess.run(pred, feed_dict= {X: voting_data})
К сожалению, строка "new_saver.restore (...)" вызывает следующее сообщение об ошибке:
NotFoundError (см. Выше для отслеживания): Плотный ключ / смещение не найдено в контрольной точке [[Узел: save / RestoreV2 = RestoreV2 [dtypes = [DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device = "/ job: localhost /»реплика: 0 / задача: 0 / устройство: ЦП: 0 "] (_arg_save / Const_0_0, сохранить / RestoreV2 / tenor_names, сохранить / RestoreV2 / shape_and_slices)]] [[Узел: сохранить / RestoreV2 / _9 = _Recvclient_terminated = false, recv_device ="/ работа: локальный / реплика: 0 / задача: 0 / устройства: GPU: 0",send_device = "/ job: localhost / replica: 0 / task: 0 / device: CPU: 0", send_device_incarnation = 1, тензор_имя = "edge_14_save / RestoreV2", тензор_типа = DT_FLOAT, _device = "/ job: localhost / реплика: 0/ task: 0 / device: GPU: 0 "]]
Я вернулся к первому блоку кода, чтобы попробовать эти изменения:
a) saver = tf.train.Saver (max_to_keep = 1) -> saver = tf.train.Saver (tf.global_variables (), max_to_keep = 1)
b) saver = tf.train.Saver (max_to_keep = 1) -> saver = tf.train.Saver (tf. trainable_variables (), max_to_keep = 1)
И все же, я все еще получаю то же сообщение об ошибке.
Есть предложения?
Большое спасибо, Иван