keras输出中间层结果

转载自keras输出中间层结果的2种方法

使用函数模型API,新建一个model,将输入和输出定义为原来的model的输入和想要的那一层的输出,然后重新进行predict.

#coding=utf-8
import seaborn as sbn
import pylab as plt
import theano
from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.models import Model

model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(16, activation='relu',name="Dense_1"))
model.add(Dense(1, activation='sigmoid',name="Dense_2"))
model.compile(optimizer='rmsprop', loss='binary_crossentropy',
              metrics=['accuracy'])

# Generate dummy data
import numpy as np
#假设训练和测试使用同一组数据
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)

从定义的网络的其中一层输出:

#已有的model在load权重过后
#取某一层的输出为输出新建为model,采用函数模型
dense1_layer_model = Model(inputs=model.input,
                                     outputs=model.get_layer('Dense_1').output)

然后进行预测

#以这个model的预测值作为输出
dense1_output = dense1_layer_model.predict(data)

print dense1_output.shape
print dense1_output[0]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.使用函数模型API,新建一个model,将输入和输出定义为原来的model的输入和想要的那一层的输出,然后重新...
    zkeenly阅读 2,565评论 0 0
  • Keras 源码分析 此文档中,凡代码里用pass,均系省略源码以便阅读,起“本枝百世”之用。此注明者,乃pass...
    yangminz阅读 31,903评论 5 34
  • 一个人年少的时候,我觉得孤独是很酷的一件事。长大之后,我觉得孤独是一件很凄凉的事。现在,我觉得孤独不是一件事。一个...
    Rockandrolla阅读 374评论 0 2
  • 好久没写东西啦。最近忙着工作,没时间思考人生,也不会去想一些有的没的。这不,一放假闲下来,就开始胡思乱想了。 我想...
    海绵阿毛阅读 539评论 0 0
  • 时光的年轮终于走到了2017年的终点。 在这辞旧迎新的时刻,首先我要真诚地说声感谢:感谢阳光,为...
    一路花香2阅读 243评论 0 0