如何使用从训练过的keras模型中提取的张量流模型

时间:2017-01-23 16:01:21

标签: python machine-learning tensorflow neural-network keras

我想使用keras框架构建和训练神经网络。我配置keras它将使用Tensorflow作为后端。在我使用keras训练模型后,我尝试仅使用Tensorflow。我可以访问会话并获取张量流图。但我不知道如何使用张量流图来进行预测。

我使用以下教程构建网络 http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/

在train()方法中我只使用keras构建和训练模型并保存keras和tensorflow模型

在eval()方法中

这是我的代码:

from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import keras.backend.tensorflow_backend as K
import tensorflow as tf
import numpy

sess = tf.Session()
K.set_session(sess)

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]


def train():
    # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
    model.add(Dense(8, init='uniform', activation='relu'))
    model.add(Dense(1, init='uniform', activation='sigmoid'))

    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics['accuracy'])

    # Fit the model
    model.fit(X, Y, nb_epoch=10, batch_size=10)

    # evaluate the model
    scores = model.evaluate(X, Y)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100))

    # serialize model to JSON
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save_weights("model.h5")

    # save tensorflow modell
    saver = tf.train.Saver()
    save_path = saver.save(sess, "model")

def eval():
    # load json and create model
    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)

    # load weights into new model
    loaded_model.load_weights("model.h5")

    # evaluate loaded model on test data
    loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    score = loaded_model.evaluate(X, Y, verbose=0)
    loaded_model.predict(X)
    print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

    # load tensorflow model
    sess = tf.Session()
    saver = tf.train.import_meta_graph('model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # TODO try to predict with the tensorflow model only
    # without using keras functions

我可以访问keras框架为我构建的张量流图(sess.graph),但我不知道如何使用张量流图来预测。我知道如何构建张量流图并在generell中使用它进行预测,但不能使用模型keras为我构建。

1 个答案:

答案 0 :(得分:3)

您需要从Keras模型定义中获取输入和输出张量,然后获取当前的TensorFlow会话。然后,您只能使用TensorFlow进行评估。假设modelloaded_modelx是您的培训数据。

sess = K.get_session()
input_tensor = model.input
output_tensor = model.output

output_tensor.eval(feed_dict={input_tensor: x}, session=sess)