您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:TensorFlow-抽取模型某一层特征 keras输出中间层结果的2种方法

51自学网 2020-09-19 17:17:32
  python
这篇教程TensorFlow-抽取模型某一层特征 keras输出中间层结果的2种方法写得很实用,希望能帮到您。

TensorFlow-抽取模型某一层特征   原文链接

深度学习具有强大的特征表达能力。有时候我们训练好分类模型,并不想用来进行分类,而是用来提取特征用于其他任务,比如相似图片计算。接下来讲下如何使用TensorFlow提取特征。

1.必须在模型中命名好要提取的那一层,如下

self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total], name='h_pool_flat')			

2.通过调用sess.run()来获取h_pool_flat层特征


 
  1. feature = graph.get_operation_by_name("h_pool_flat").outputs[0]
  2. batch_predictions, batch_feature = \
  3. sess.run([predictions, feature], {input_x: x_test_batch, dropout_keep_prob: 1.0})

 

 keras输出中间层结果的2种方法  原文链接

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]

2.因为我的后端是使用的theano,所以还可以考虑使用theano的函数:


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

 


深度学习优化函数详解 Nesterov accelerated gradient (NAG)
获取Pytorch中间某一层权重或者特征
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。