keras模型可视化,层可视化及kernel可视化实例
作者:xinfeng2005 时间:2021-02-20 00:45:25
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()
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()
model.layers[1]
model.layers[5]
model.layers[-1]
来源:https://blog.csdn.net/xinfeng2005/article/details/78697415
标签:keras,kernel,可视化
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP session反序列化漏洞深入探究
2023-05-30 04:53:04
![](https://img.aspxhome.com/file/2023/7/55367_0s.png)
用python编写一个图片拼接工具
2023-09-01 18:31:52
![](https://img.aspxhome.com/file/2023/9/62599_0s.jpg)
用 onerror 获取错误信息 js Debug
2008-11-03 19:08:00
Python 多张图片合并成一个pdf的参考示例
2021-10-15 23:32:45
python paramiko实现ssh远程访问的方法
2021-07-17 23:03:55
在网页设计中,如何使用图标来支持内容?[译]
2009-03-16 16:35:00
![](https://img.aspxhome.com/file/UploadPic/20093/16/280slides-85s.jpg)
Python的垃圾回收机制详解
2023-06-03 16:03:24
oracle执行cmd的实现方法
2009-04-24 12:10:00
SQL 外链接操作小结 inner join left join right join
2008-03-12 11:56:00
Python time模块时间获取和转换方法
2022-06-07 11:14:30
Python依赖包迁移到断网环境操作
2021-06-27 06:58:29
python实现获取序列中最小的几个元素
2023-12-24 19:11:32
python实现五子棋游戏(pygame版)
2021-09-15 16:01:42
![](https://img.aspxhome.com/file/2023/6/65916_0s.gif)
HTML和SEO基础知识:H标签全透视
2010-09-21 16:45:00
![](https://img.aspxhome.com/file/UploadPic/20109/21/1412060-45s.jpg)
css中absolute与relative的区别
2007-11-17 08:04:00
![](https://img.aspxhome.com/file/UploadPic/20071/200713110612782s.gif)
Python语言描述机器学习之Logistic回归算法
2023-08-31 01:14:35
![](https://img.aspxhome.com/file/2023/9/75129_0s.jpg)
在Yii框架中使用PHP模板引擎Twig的例子
2023-11-14 11:30:30
从浏览器想开去
2008-07-29 12:52:00
Python调用飞书发送消息的示例
2022-10-20 14:21:23
试试把xml和javascript写到同一个文件里面
2009-10-02 16:53:00