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中struct模块对字节流/二进制流的操作教程
Jan 21 Python
浅谈django model postgres的json字段编码问题
Jan 05 Python
Python中协程用法代码详解
Feb 10 Python
用python简单实现mysql数据同步到ElasticSearch的教程
May 30 Python
pandas DataFrame索引行列的实现
Jun 04 Python
Python 窗体(tkinter)按钮 位置实例
Jun 13 Python
VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法详解
Jul 01 Python
新手如何发布Python项目开源包过程详解
Jul 11 Python
使用Python操作ArangoDB的方法步骤
Feb 02 Python
解决pycharm下pyuic工具使用的问题
Apr 08 Python
Win10用vscode打开anaconda环境中的python出错问题的解决
May 25 Python
Python可视化神器pyecharts之绘制地理图表练习
Jul 07 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
javascript 函数式编程
2007/08/16 Javascript
JQuery UI皮肤定制
2009/07/27 Javascript
Jquery实现弹出层分享微博插件具备动画效果
2013/04/03 Javascript
PHP中CURL的几个经典应用实例
2015/01/23 Javascript
如何改进javascript代码的性能
2015/04/02 Javascript
jQuery实现的产品自动360度旋转展示特效源码分享
2015/08/21 Javascript
jQuery多条件筛选如何实现
2015/11/04 Javascript
JS实现两周内自动登录功能
2017/03/23 Javascript
js实现登录注册框手机号和验证码校验(前端部分)
2017/09/28 Javascript
微信小程序vant弹窗组件的实现方式
2020/02/21 Javascript
Javascript地址引用代码实例解析
2020/02/25 Javascript
《javascript设计模式》学习笔记三:Javascript面向对象程序设计单例模式原理与实现方法分析
2020/04/07 Javascript
vue内置组件keep-alive事件动态缓存实例
2020/10/30 Javascript
Python实现多线程下载文件的代码实例
2014/06/01 Python
Python实现短网址ShortUrl的Hash运算实例讲解
2015/08/10 Python
Python简单实现安全开关文件的两种方式
2016/09/19 Python
Python使用flask框架操作sqlite3的两种方式
2018/01/31 Python
基于Python socket的端口扫描程序实例代码
2018/02/09 Python
python3中zip()函数使用详解
2018/06/29 Python
python实现事件驱动
2018/11/21 Python
python for和else语句趣谈
2019/07/02 Python
Python函数必须先定义,后调用说明(函数调用函数例外)
2020/06/02 Python
使用Python判断一个文件是否被占用的方法教程
2020/12/16 Python
Nice Kicks网上商店:ShopNiceKicks.com
2018/12/25 全球购物
美国家居装饰店:Z Gallerie
2020/12/28 全球购物
对于没有初始化的变量的初始值可以作怎样的假定
2014/10/12 面试题
如何为DataGridView添加一个定制的Column Type
2014/01/21 面试题
Shell如何接收变量输入
2012/09/24 面试题
工程专业毕业生自荐信范文
2013/12/25 职场文书
建筑工地标语
2014/06/18 职场文书
2014年建筑工作总结
2014/11/26 职场文书
2015年小学体育教师工作总结
2015/10/23 职场文书
2016年党风廉政建设承诺书
2016/03/25 职场文书
基于Golang 高并发问题的解决方案
2021/05/08 Golang
《现实主义勇者的王国再建记》第三弹OST全曲试听片段公开
2022/04/04 日漫
关于mysql中string和number的转换问题
2022/06/14 MySQL