zoukankan      html  css  js  c++  java
  • Keras 获取中间某一层输出

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

     1 #coding=utf-8
     2 import seaborn as sbn
     3 import pylab as plt
     4 import theano
     5 from keras.models import Sequential
     6 from keras.layers import Dense,Activation
     7 
     8 
     9 from keras.models import Model
    10 
    11 model = Sequential()
    12 model.add(Dense(32, activation='relu', input_dim=100))
    13 model.add(Dense(16, activation='relu',name="Dense_1"))
    14 model.add(Dense(1, activation='sigmoid',name="Dense_2"))
    15 model.compile(optimizer='rmsprop',
    16 loss='binary_crossentropy',
    17 metrics=['accuracy'])
    18 
    19 # Generate dummy data
    20 import numpy as np
    21 #假设训练和测试使用同一组数据
    22 data = np.random.random((1000, 100))
    23 labels = np.random.randint(2, size=(1000, 1))
    24 
    25 # Train the model, iterating on the data in batches of 32 samples
    26 model.fit(data, labels, epochs=10, batch_size=32)
    27 #已有的model在load权重过后
    28 #取某一层的输出为输出新建为model,采用函数模型
    29 dense1_layer_model = Model(inputs=model.input,
    30 outputs=model.get_layer('Dense_1').output)
    31 #以这个model的预测值作为输出
    32 dense1_output = dense1_layer_model.predict(data)
    33 
    34 print dense1_output.shape
    35 print dense1_output[0]
    36 
    37 
    38 2.因为我的后端是使用的theano,所以还可以考虑使用theano的函数:
    39 #这是一个theano的函数
    40 dense1 = theano.function([model.layers[0].input],model.layers[1].output,allow_input_downcast=True)
    41 dense1_output = dense1(data) #visualize these images's FC-layer feature
    42 print dense1_output[0]

    效果应该是一样的。

    ---------------------
    作者:哈哈进步
    来源:CSDN
    原文:https://blog.csdn.net/hahajinbu/article/details/77982721
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    (转)Linux 信号说明列表
    linux下socket函数之listen的参数backlog
    (转)auto_ptr与shared_ptr
    (转)关于两次fork
    收集外链
    (转+整理)Linux下Makefile的automake生成全攻略
    LINUX socket编程(转载)errno.h
    (转) socket编程——sockaddr_in结构体操作
    k Nearest Neighbor Search by CUDA
    CUDA Anisotropic Diffusion on a 2D Image
  • 原文地址:https://www.cnblogs.com/as3asddd/p/10129241.html
Copyright © 2011-2022 走看看