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使用代理抓取网站图片(多线程)
Mar 14 Python
python将图片文件转换成base64编码的方法
Mar 14 Python
用map函数来完成Python并行任务的简单示例
Apr 02 Python
Python正则表达式非贪婪、多行匹配功能示例
Aug 08 Python
Tornado高并发处理方法实例代码
Jan 15 Python
Python3实现的画图及加载图片动画效果示例
Jan 19 Python
python将一组数分成每3个一组的实例
Nov 14 Python
详解Pandas之容易让人混淆的行选择和列选择
Jul 10 Python
Python图像处理库PIL的ImageFont模块使用介绍
Feb 26 Python
keras 指定程序在某块卡上训练实例
Jun 22 Python
python删除指定列或多列单个或多个内容实例
Jun 28 Python
Python编程编写完善的命令行工具
Sep 15 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
Zerg兵种介绍
2020/03/14 星际争霸
如何使用PHP计算上一个月的今天
2013/05/23 PHP
浅析PKI加密解密 OpenSSL
2013/07/01 PHP
php实现MySQL数据库备份与还原类实例
2014/12/09 PHP
浅谈本地WAMP环境的搭建
2015/05/13 PHP
番茄的表单验证类代码修改版
2008/07/18 Javascript
基于jquery的滚动鼠标放大缩小图片效果
2011/10/27 Javascript
javascript实现动态导入js与css等静态资源文件的方法
2015/07/25 Javascript
JavaScript驾驭网页-DOM
2016/03/24 Javascript
浅谈jquery中next与siblings的区别
2016/10/27 Javascript
深入对Vue.js $watch方法的理解
2017/03/20 Javascript
js模仿微信朋友圈计算时间显示几天/几小时/几分钟/几秒之前
2017/04/27 Javascript
Javascript之图片的延迟加载的实例详解
2017/07/24 Javascript
修改vue+webpack run build的路径方法
2018/09/01 Javascript
Vue.js特性Scoped Slots的浅析
2019/02/20 Javascript
JavaScript实现拖拽盒子效果
2020/02/06 Javascript
微信小程序多列表渲染数据开关互不影响的实现
2020/06/05 Javascript
[02:53]DOTA2亚洲邀请赛 NewBee战队巡礼
2015/02/03 DOTA
[03:37]2015国际邀请赛第四日现场精彩集锦
2015/08/08 DOTA
Django rest framework基本介绍与代码示例
2018/01/26 Python
python调用虹软2.0第三版的具体使用
2019/02/22 Python
Python3.5集合及其常见运算实例详解
2019/05/01 Python
selenium+PhantomJS爬取豆瓣读书
2019/08/26 Python
详解Python3中的 input() 函数
2020/03/18 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
2020/07/14 Python
Win10环境中如何实现python2和python3并存
2020/07/20 Python
python实现逻辑回归的示例
2020/10/09 Python
html5配合css3实现带提示文字的输入框(摆脱js)
2013/03/08 HTML / CSS
Melijoe英国官网:法国儿童时尚网站
2016/11/18 全球购物
英国手机零售商:Carphone Warehouse
2018/06/06 全球购物
橄榄树药房:OLIVEDA
2019/09/01 全球购物
乌克兰珠宝大卖场:Zlato.ua
2020/09/27 全球购物
小学数学教学反思
2014/02/02 职场文书
《最可爱的人》教学反思
2014/02/14 职场文书
挂科检讨书范文
2014/02/20 职场文书
2014年工程部工作总结
2014/11/25 职场文书