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的另外几种语言实现
Jan 29 Python
Python基于tkinter模块实现的改名小工具示例
Jul 27 Python
[原创]Python入门教程4. 元组基本操作
Oct 31 Python
python如何查看微信消息撤回
Nov 27 Python
解决pycharm回车之后不能换行或不能缩进的问题
Jan 16 Python
详解Python计算机视觉 图像扭曲(仿射扭曲)
Mar 27 Python
Django的models模型的具体使用
Jul 15 Python
python中for循环变量作用域及用法详解
Nov 05 Python
解决pycharm同一目录下无法import其他文件
Feb 12 Python
使用卷积神经网络(CNN)做人脸识别的示例代码
Mar 27 Python
什么是python的必选参数
Jun 21 Python
python实现代码审查自动回复消息
Feb 01 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 导出数据到淘宝助手CSV的方法分享
2010/02/27 PHP
PHP开发中常用的三个表单验证函数使用小结
2010/03/03 PHP
微信公众号点击菜单即可打开并登录微站的实现方法
2014/11/14 PHP
PHP接口并发测试的方法(推荐)
2016/12/15 PHP
PHP编程获取图片的主色调的方法【基于Imagick扩展】
2017/08/02 PHP
php面向对象程序设计入门教程
2019/06/22 PHP
jquery 简短几句代码实现给元素动态添加及获取提示信息
2011/09/01 Javascript
JSONP获取Twitter和Facebook文章数的具体步骤
2014/02/24 Javascript
JQuery下拉框应用示例介绍
2014/04/23 Javascript
Javascript中设置默认参数值示例
2014/09/11 Javascript
深入理解JavaScript中的对象
2015/06/04 Javascript
jQuery Validate验证框架经典大全
2015/09/23 Javascript
图片旋转、鼠标滚轮缩放、镜像、切换图片js代码
2020/12/13 Javascript
jQuery Mobile 和 Kendo UI 的比较
2016/05/05 Javascript
checkbox批量选中,获取选中项的值的简单实例
2016/06/28 Javascript
详解使用jQuery.i18n.properties实现js国际化
2018/05/04 jQuery
详解基于Vue-cli搭建的项目如何和后台交互
2018/06/29 Javascript
vue中动态添加class类名的方法
2018/09/05 Javascript
微信小程序 setData 对 data数据影响问题
2019/04/18 Javascript
[01:06]DOTA2小知识课堂 Ep.02 吹风竟可解梦境缠绕
2019/12/05 DOTA
python计算最小优先级队列代码分享
2013/12/18 Python
Python爬虫实现(伪)球迷速成
2018/06/10 Python
python使用循环打印所有三位数水仙花数的实例
2018/11/13 Python
Python面向对象特殊属性及方法解析
2020/09/16 Python
详解Python中list[::-1]的几种用法
2020/11/16 Python
运行python提示no module named sklearn的解决方法
2020/11/29 Python
HTML5 audio标签使用js进行播放控制实例
2015/04/24 HTML / CSS
Sephora丝芙兰马来西亚官方网站:国际化妆品购物
2018/03/15 全球购物
澳大利亚家用电器在线商店:Billy Guyatts
2020/05/05 全球购物
自动化专业本科毕业生求职信
2013/10/20 职场文书
服务标语大全
2014/06/18 职场文书
员工工作及收入证明
2014/10/28 职场文书
2015年12.4全国法制宣传日活动总结
2015/03/24 职场文书
意外事故赔偿协议书
2016/03/22 职场文书
动漫APP软件排行榜前十名,半次元上榜,第一款由腾讯公司推出
2022/03/18 杂记
Java数组详细介绍及相关工具类
2022/04/14 Java/Android