keras模型可视化,层可视化及kernel可视化实例


Posted in Python onJanuary 24, 2020

keras模型可视化:

model:

model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model.add(ZeroPadding2D((1,1), input_shape=(38, 38, 1)))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
# model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation='relu', padding='same',))
# model.add(Conv2D(64, (3, 3), activation='relu', padding='same',))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(128, (3, 3), activation='relu', padding='same',))
# model.add(Conv2D(128, (3, 3), activation='relu', padding='same',))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(AveragePooling2D((5,5)))

model.add(Flatten())
# model.add(Dense(512, activation='relu'))
# model.add(Dropout(0.5))
model.add(Dense(label_size, activation='softmax'))

1.层可视化:

test_x = []
img_src = cv2.imdecode(np.fromfile(r'c:\temp.tif', dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img_src, (38, 38), interpolation=cv2.INTER_CUBIC)
# img = np.random.randint(0,255,(38,38))
img = (255 - img) / 255
img = np.reshape(img, (38, 38, 1))
test_x.append(img)

###################################################################
layer = model.layers[1]
weight = layer.get_weights()
# print(weight)
print(np.asarray(weight).shape)
model_v1 = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model_v1.add(ZeroPadding2D((1, 1), input_shape=(38, 38, 1)))
model_v1.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
# model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model_v1.layers[1].set_weights(weight)

re = model_v1.predict(np.array(test_x))
print(np.shape(re))
re = np.transpose(re, (0,3,1,2))
for i in range(32):
  plt.subplot(4,8,i+1)
  plt.imshow(re[0][i]) #, cmap='gray'
plt.show()

##################################################################
model_v2 = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model_v2.add(ZeroPadding2D((1, 1), input_shape=(38, 38, 1)))
model_v2.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
# model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model_v2.add(BatchNormalization())
model_v2.add(MaxPooling2D(pool_size=(2, 2)))
model_v2.add(Dropout(0.25))

model_v2.add(Conv2D(64, (3, 3), activation='relu', padding='same', ))
print(len(model_v2.layers))
layer1 = model.layers[1]
weight1 = layer1.get_weights()
model_v2.layers[1].set_weights(weight1)
layer5 = model.layers[5]
weight5 = layer5.get_weights()
model_v2.layers[5].set_weights(weight5)
re2 = model_v2.predict(np.array(test_x))
re2 = np.transpose(re2, (0,3,1,2))
for i in range(64):
  plt.subplot(8,8,i+1)
  plt.imshow(re2[0][i]) #, cmap='gray'
plt.show()

##################################################################
model_v3 = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model_v3.add(ZeroPadding2D((1, 1), input_shape=(38, 38, 1)))
model_v3.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
# model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model_v3.add(BatchNormalization())
model_v3.add(MaxPooling2D(pool_size=(2, 2)))
model_v3.add(Dropout(0.25))

model_v3.add(Conv2D(64, (3, 3), activation='relu', padding='same', ))
# model.add(Conv2D(64, (3, 3), activation='relu', padding='same',))
model_v3.add(BatchNormalization())
model_v3.add(MaxPooling2D(pool_size=(2, 2)))
model_v3.add(Dropout(0.25))

model_v3.add(Conv2D(128, (3, 3), activation='relu', padding='same', ))

print(len(model_v3.layers))
layer1 = model.layers[1]
weight1 = layer1.get_weights()
model_v3.layers[1].set_weights(weight1)
layer5 = model.layers[5]
weight5 = layer5.get_weights()
model_v3.layers[5].set_weights(weight5)
layer9 = model.layers[9]
weight9 = layer9.get_weights()
model_v3.layers[9].set_weights(weight9)
re3 = model_v3.predict(np.array(test_x))
re3 = np.transpose(re3, (0,3,1,2))
for i in range(121):
  plt.subplot(11,11,i+1)
  plt.imshow(re3[0][i]) #, cmap='gray'
plt.show()

keras模型可视化,层可视化及kernel可视化实例

2.kernel可视化:

def process(x):
  res = np.clip(x, 0, 1)
  return res

def dprocessed(x):
  res = np.zeros_like(x)
  res += 1
  res[x < 0] = 0
  res[x > 1] = 0
  return res

def deprocess_image(x):
  x -= x.mean()
  x /= (x.std() + 1e-5)
  x *= 0.1
  x += 0.5
  x = np.clip(x, 0, 1)
  x *= 255
  x = np.clip(x, 0, 255).astype('uint8')
  return x

for i_kernal in range(64):
  input_img=model.input
  loss = K.mean(model.layers[5].output[:, :,:,i_kernal])
  # loss = K.mean(model.output[:, i_kernal])
  # compute the gradient of the input picture wrt this loss
  grads = K.gradients(loss, input_img)[0]
  # normalization trick: we normalize the gradient
  grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)
  # this function returns the loss and grads given the input picture
  iterate = K.function([input_img, K.learning_phase()], [loss, grads])
  # we start from a gray image with some noise
  np.random.seed(0)
  num_channels=1
  img_height=img_width=38
  input_img_data = (255- np.random.randint(0,255,(1, img_height, img_width, num_channels))) / 255.
  failed = False
  # run gradient ascent
  print('####################################',i_kernal+1)
  loss_value_pre=0
  for i in range(10000):
    # processed = process(input_img_data)
    # predictions = model.predict(input_img_data)
    loss_value, grads_value = iterate([input_img_data,1])
    # grads_value *= dprocessed(input_img_data[0])
    if i%1000 == 0:
      # print(' predictions: ' , np.shape(predictions), np.argmax(predictions))
      print('Iteration %d/%d, loss: %f' % (i, 10000, loss_value))
      print('Mean grad: %f' % np.mean(grads_value))
      if all(np.abs(grads_val) < 0.000001 for grads_val in grads_value.flatten()):
        failed = True
        print('Failed')
        break
      # print('Image:\n%s' % str(input_img_data[0,0,:,:]))
      if loss_value_pre != 0 and loss_value_pre > loss_value:
        break
      if loss_value_pre == 0:
        loss_value_pre = loss_value

      # if loss_value > 0.99:
      #   break

    input_img_data += grads_value * 1 #e-3
  plt.subplot(8, 8, i_kernal+1)
  # plt.imshow((process(input_img_data[0,:,:,0])*255).astype('uint8'), cmap='Greys') #cmap='Greys'
  img_re = deprocess_image(input_img_data[0])
  img_re = np.reshape(img_re, (38,38))
  plt.imshow(img_re, cmap='Greys') #cmap='Greys'
  # plt.show()
plt.show()

keras模型可视化,层可视化及kernel可视化实例

model.layers[1]

keras模型可视化,层可视化及kernel可视化实例

model.layers[5]

keras模型可视化,层可视化及kernel可视化实例

model.layers[-1]

以上这篇keras模型可视化,层可视化及kernel可视化实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用基于Python的Tornado框架的HTTP客户端的教程
Apr 24 Python
Python的Django框架中模板碎片缓存简介
Jul 24 Python
Python中使用支持向量机SVM实践
Dec 27 Python
python脚本实现验证码识别
Jun 07 Python
python+pandas+时间、日期以及时间序列处理方法
Jul 10 Python
对Python 3.5拼接列表的新语法详解
Nov 08 Python
解决pycharm py文件运行后停止按钮变成了灰色的问题
Nov 29 Python
python3.6使用urllib完成下载的实例
Dec 19 Python
在Python 中同一个类两个函数间变量的调用方法
Jan 31 Python
Flask框架学习笔记之模板操作实例详解
Aug 15 Python
windows+vscode安装paddleOCR运行环境的步骤
Nov 11 Python
MoviePy简介及Python视频剪辑自动化
Dec 18 Python
keras 特征图可视化实例(中间层)
Jan 24 #Python
基于keras输出中间层结果的2种实现方式
Jan 24 #Python
tensorflow 保存模型和取出中间权重例子
Jan 24 #Python
tensorflow 模型权重导出实例
Jan 24 #Python
在Tensorflow中查看权重的实现
Jan 24 #Python
tensorflow求导和梯度计算实例
Jan 23 #Python
Tensorflow的梯度异步更新示例
Jan 23 #Python
You might like
用PHP实现小型站点广告管理
2006/10/09 PHP
php 问卷调查结果统计
2015/10/08 PHP
PHP的压缩函数实现:gzencode、gzdeflate和gzcompress的区别
2016/01/27 PHP
PHP针对字符串开头和结尾的判断方法
2016/07/11 PHP
许愿墙中用到的函数
2006/10/07 Javascript
jQuery+HTML5实现手机摇一摇换衣特效
2015/06/05 Javascript
js数组去重的5种算法实现
2015/11/04 Javascript
jQuery实现订单提交页发送短信功能前端处理方法
2016/07/04 Javascript
简单实现js轮播图效果
2017/07/14 Javascript
Angular中自定义Debounce Click指令防止重复点击
2017/07/26 Javascript
JavaScript设计模式之享元模式实例详解
2019/01/17 Javascript
Vue 样式切换及三元判断样式关联操作
2020/08/09 Javascript
[01:33]一分钟玩转DOTA2第三弹:DOTA2&DotA快捷操作大对比
2014/06/04 DOTA
[02:42]2014DOTA2国际邀请赛 三冰专访:我会打到Ti20
2014/07/13 DOTA
python 多线程应用介绍
2012/12/19 Python
编写自定义的Django模板加载器的简单示例
2015/07/21 Python
Python实现读取Properties配置文件的方法
2018/03/29 Python
Python3读取Excel数据存入MySQL的方法
2018/05/04 Python
在cmd中运行.py文件: python的操作步骤
2018/05/12 Python
python3-flask-3将信息写入日志的实操方法
2019/11/12 Python
python isinstance函数用法详解
2020/02/13 Python
python GUI库图形界面开发之PyQt5控件数据拖曳Drag与Drop详细使用方法与实例
2020/02/27 Python
keras:model.compile损失函数的用法
2020/07/01 Python
澳大利亚在线生活方式商店:Mytopia
2018/07/08 全球购物
美国折衷生活方式品牌:Robert Graham
2018/07/13 全球购物
英国老牌潮鞋店:Offspring
2019/08/19 全球购物
华为菲律宾官方网站:HUAWEI Philippines
2021/02/23 全球购物
工作表扬信的范文
2014/01/10 职场文书
汽车专业学生自我评价
2014/01/19 职场文书
城建学院毕业生自荐信
2014/01/31 职场文书
小学生元旦感言
2014/02/26 职场文书
干部考核评语
2014/04/29 职场文书
团代会宣传工作方案
2014/05/08 职场文书
幼儿园教师个人总结
2015/02/05 职场文书
小学公民道德宣传日活动总结
2015/03/23 职场文书
解放思想大讨论活动总结
2015/05/09 职场文书