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 相关文章推荐
django上传图片并生成缩略图方法示例
Dec 11 Python
Python实现的爬虫刷回复功能示例
Jun 07 Python
python版DDOS攻击脚本
Jun 12 Python
Python获取时间戳代码实例
Sep 24 Python
python爬虫 Pyppeteer使用方法解析
Sep 28 Python
Python Django框架模板渲染功能示例
Nov 08 Python
Python动态导入模块和反射机制详解
Feb 18 Python
Python线程协作threading.Condition实现过程解析
Mar 12 Python
Python getattr()函数使用方法代码实例
Aug 10 Python
如何使用Python对NetCDF数据做空间相关分析
Apr 21 Python
OpenCV-Python实现油画效果的实例
Jun 08 Python
Python上下文管理器Content Manager
Jun 26 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/12/06 PHP
php出现内存位置访问无效错误问题解决方法
2014/08/16 PHP
深入浅析PHP的session反序列化漏洞问题
2017/06/15 PHP
PHP设计模式之装饰器模式定义与用法详解
2018/04/02 PHP
javascript开发中因空格引发的错误
2010/11/08 Javascript
Dom操作之兼容技巧分享
2011/09/20 Javascript
jquery 面包屑导航 具体实现
2013/06/05 Javascript
jQuery中的编程范式详解
2014/12/15 Javascript
jquery控制背景音乐开关与自动播放提示音的方法
2015/02/06 Javascript
省市区三级联动下拉框菜单javascript版
2015/08/11 Javascript
简要了解jQuery移动web开发的响应式布局设计
2015/12/04 Javascript
[原创]js实现保存文本框内容为本地文件兼容IE,chrome,火狐浏览器
2018/02/14 Javascript
Vue-component全局注册实例
2018/09/06 Javascript
深入学习js函数的隐式参数 arguments 和 this
2019/06/24 Javascript
JQuery获得内容和属性方法解析
2020/05/30 jQuery
Vue实现开关按钮拖拽效果
2020/09/22 Javascript
[48:31]完美世界DOTA2联赛PWL S3 DLG vs Phoenix 第二场 12.17
2020/12/19 DOTA
python安装numpy&amp;安装matplotlib&amp; scipy的教程
2017/11/02 Python
使用python实现ANN
2017/12/20 Python
Python实现上下班抢个顺风单脚本
2018/02/07 Python
Python统计单词出现的次数
2018/04/04 Python
python 查找文件名包含指定字符串的方法
2018/06/05 Python
关于pymysql模块的使用以及代码详解
2019/09/01 Python
Pytorch 图像变换函数集合小结
2021/02/01 Python
原生canvas制作画图小工具的踩坑和爬坑
2020/06/09 HTML / CSS
Cotton On香港网站:澳洲时装连锁品牌
2018/11/01 全球购物
瑞典网上购买现代和复古家具:Reforma
2019/10/21 全球购物
运动会领导邀请函
2014/01/10 职场文书
公司周年庆典邀请函
2014/01/12 职场文书
黄河的主人教学反思
2014/02/07 职场文书
2014教师党员自我评议(5篇)
2014/09/20 职场文书
个人承诺书格式范文
2015/04/29 职场文书
2016年大学生实习单位评语
2015/12/01 职场文书
基层医务人员三严三实心得体会
2016/01/05 职场文书
基于PyQT5制作一个桌面摸鱼工具
2022/02/15 Python
单机多实例部署 MySQL8.0.20
2022/05/15 MySQL