Keras & Theano get output of an intermediate layer

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

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])
2.因为我的后端是使用的theano,所以还可以考虑使用theano的函数:

#这是一个theano的函数
dense1 = theano.function([model.layers[0].input],model.layers[1].output,allow_input_downcast=True)
dense1_output = dense1(data) #visualize these images's FC-layer feature
print(dense1_output[0])

效果应该是一样的。

 

来源:https://blog.csdn.net/hahajinbu/article/details/77982721

 
 
 
 
 
 
 

最新文章

  1. Troubleshooting:重新安装Vertica建库后无法启动
  2. MySQL日期时间函数大全(转)
  3. Java实现分页数据获取CachedRowSet
  4. 《C++ primer》--第7章
  5. 166. Fraction to Recurring Decimal
  6. 【原】Spark Rpc通信源码分析
  7. Developer‘s提升开发效率的工具和插件或编程语言
  8. FpGrowth算法
  9. 使用Maven管理依赖JAR文件,自定义项目布局,利用ANT生成不同的发布包
  10. Html基础详解之(jquery)
  11. 最全DOS的CMD命令,程序员必会
  12. 总结:当静态路由和BGP同时存在时路由优选BGP的两种方法
  13. PAT Basic 1002
  14. 前端开发环境之GRUNT自动WATCH压缩JS文件与编译SASS文件环境下Ruby安装sass常见错误分析
  15. void类型详解
  16. Java ArrayList源码剖析
  17. 44 道 JavaScript 难题
  18. python-day65-django基础
  19. ios开发UI篇—UITextfield
  20. 原生canvas写的飞机游戏

热门文章

  1. 使用git工具将本地电脑上的代码上传至GitHub
  2. Go语言学习笔记(4)——数组和切片
  3. inline-block各浏览器兼容以及水平间隙问题解决方案
  4. SourceTree跳过Atlassian账号,免登陆,跳过初始设置
  5. Android 开发服务类 03_ServletForGETMethod
  6. Struts 2初体验
  7. 关于offsetTop的误解
  8. redis集群与分片(2)-Redis Cluster集群的搭建与实践
  9. HDU 5253 连接的管道(Kruskal算法求解MST)
  10. OpenDigg前端开源项目月报201704