나는 tensorflow github에서 신경 네트워크의 간단한 예제를 가져 와서 두 부분으로 나누려고했습니다. 첫 번째 파트는 training + test이고 두 번째 파트는 복원이 필요한 테스트 파트를 분리하는 것입니다. 복원이 작동하는 것처럼 보이지만 예측 기능을 찾을 수 없습니다.Tensor Flow Estimator 템플릿 기반 모델 저장 및 복원
from __future__ import print_function
from tensorflow.python.saved_model import builder as saved_model_builder
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import shutil
matplotlib.use('TkAgg')
# Parameters
learning_rate = 0.1
num_steps = 1000
batch_size = 128
display_step = 100
# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
#init = tf.initialize_all_variables()
sess = tf.Session()
# Define the input function for training
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': mnist.train.images}, y=mnist.train.labels,
batch_size=batch_size, num_epochs=None, shuffle=True)
# Define the neural network
def neural_net(x_dict):
# TF Estimator input is a dict, in case of multiple inputs
x = x_dict['images']
# Hidden fully connected layer with 256 neurons
layer_1 = tf.layers.dense(x, n_hidden_1, name="layer_1")
# Hidden fully connected layer with 256 neurons
layer_2 = tf.layers.dense(layer_1, n_hidden_2, name="layer_2")
# Output fully connected layer with a neuron for each class
out_layer = tf.layers.dense(layer_2, num_classes, name="out_layer")
return out_layer
# Define the model function (following TF Estimator Template)
def model_fn(features, labels, mode):
# Build the neural network
logits = neural_net(features)
# Predictions
pred_classes = tf.argmax(logits, axis=1)
pred_probas = tf.nn.softmax(logits)
# If prediction mode, early return
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=tf.cast(labels, dtype=tf.int32)))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())
# Evaluate the accuracy of the model
acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
# TF Estimators requires to return a EstimatorSpec, that specify
# the different ops for training, evaluating, ...
estim_specs = tf.estimator.EstimatorSpec(
mode=mode,
predictions=pred_classes,
loss=loss_op,
train_op=train_op,
eval_metric_ops={'accuracy': acc_op})
return estim_specs
# Build the Estimator
model = tf.estimator.Estimator(model_fn)
# Train the Model
model.train(input_fn, steps=num_steps)
# Evaluate the Model
# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': mnist.test.images}, y=mnist.test.labels,
batch_size=batch_size, shuffle=False)
# Use the Estimator 'evaluate' method
model.evaluate(input_fn)
#model.export_savedmodel(".", input_fn)
init = tf.global_variables_initializer()
sess.run(init)
tf.add_to_collection("nn_model", model)
# Add ops to save and restore all the variables.
#saver = tf.train.Saver()
#save_path = saver.save(sess, "model/model.ckpt")
try:
shutil.rmtree("model")
except:
pass
builder = saved_model_builder.SavedModelBuilder("model")
builder.add_meta_graph_and_variables(sess, ["nn"])
builder.save()
print("Model saved in file")
# Predict single images
n_images = 4
# Get images from test set
test_images = mnist.test.images[:n_images]
# Prepare the input data
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': test_images}, shuffle=False)
# Use the model to predict the images class
preds = list(model.predict(input_fn))
# Display
for i in range(n_images):
plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
plt.show()
print("Model prediction:", preds[i])
상기 프로그램은 잘 작동 :
여기서 첫 번째 부분이다. 모든 디렉토리가 생성되는 것을 볼 때 모델을 저장합니다. 정확하게는 아닙니다.
경고 : tensorflow : nn_model을 직렬화 할 때 오류가 발생했습니다. 유형이 지원되지 않거나 항목 유형이 CollectionDef의 필드 유형과 일치하지 않습니다. '견적'개체가 어떤 속성 '이름'여기
가없는 예측() 줄을 복원하고 적용을 시도하고 실패 "적용"프로그램입니다 :
import tensorflow as tf
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
sess=tf.Session()
#First let's load meta graph and restore weights
#saver = tf.train.import_meta_graph('model/model.ckpt.meta')
#saver.restore(sess,tf.train.latest_checkpoint('nn_model'))
tf.saved_model.loader.load(sess, ["nn"], "model")
model = tf.get_collection('nn_model')
# Predict single images
n_images = 4
# Get images from test set
test_images = mnist.test.images[:n_images]
# Prepare the input data
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': test_images}, shuffle=False)
# Use the model to predict the images class
preds = list(model.predict(input_fn))
# Display
for i in range(n_images):
plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
plt.show()
print("Model prediction:", preds[i])
이주는 오류가가 :
역 추적 (마지막으로 가장 최근 통화) : 파일 "applynn.py", 라인 (35), preds에서 = 목록 (model.predict (input_fn)) AttributeError은 '모듈'개체가 예측 '에는 속성이 없습니다 '
그래서 여기에 무엇이 누락 되었습니까?