一、显示各层

# params显示:layer名,w,b
for layer_name, param in net.params.items():
print layer_name + '\t' + str(param[0].data.shape), str(param[1].data.shape) # blob显示:layer名,输出的blob维度
for layer_name, blob in net.blobs.items():
print layer_name + '\t' + str(blob.data.shape)

二、自定义函数:参数/卷积结果可视化

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import caffe
%matplotlib inline plt.rcParams['figure.figsize'] = (8, 8)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray' def show_data(data, padsize=1, padval=0):
"""Take an array of shape (n, height, width) or (n, height, width, 3)
and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""
# data归一化
data -= data.min()
data /= data.max() # 根据data中图片数量data.shape[0],计算最后输出时每行每列图片数n
n = int(np.ceil(np.sqrt(data.shape[0])))
# padding = ((图片个数维度的padding),(图片高的padding), (图片宽的padding), ....)
padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
data = np.pad(data, padding, mode='constant', constant_values=(padval, padval)) # 先将padding后的data分成n*n张图像
data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
# 再将(n, W, n, H)变换成(n*w, n*H)
data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
plt.figure()
plt.imshow(data,cmap='gray')
plt.axis('off') # 示例:显示第一个卷积层的输出数据和权值(filter)
print net.blobs['conv1'].data[0].shape
show_data(net.blobs['conv1'].data[0])
print net.params['conv1'][0].data.shape
show_data(net.params['conv1'][0].data.reshape(32*3,5,5))

三、训练过程Loss&Accuracy可视化

import matplotlib.pyplot as plt
import caffe
caffe.set_device(0)
caffe.set_mode_gpu()
# 使用SGDSolver,即随机梯度下降算法
solver = caffe.SGDSolver('/home/xxx/mnist/solver.prototxt') # 等价于solver文件中的max_iter,即最大解算次数
niter = 10000 # 每隔100次收集一次loss数据
display= 100 # 每次测试进行100次解算
test_iter = 100 # 每500次训练进行一次测试
test_interval =500 #初始化
train_loss = zeros(ceil(niter * 1.0 / display))
test_loss = zeros(ceil(niter * 1.0 / test_interval))
test_acc = zeros(ceil(niter * 1.0 / test_interval)) # 辅助变量
_train_loss = 0; _test_loss = 0; _accuracy = 0
# 进行解算
for it in range(niter):
# 进行一次解算
solver.step(1)
# 统计train loss
_train_loss += solver.net.blobs['SoftmaxWithLoss1'].data
if it % display == 0:
# 计算平均train loss
train_loss[it // display] = _train_loss / display
_train_loss = 0 if it % test_interval == 0:
for test_it in range(test_iter):
# 进行一次测试
solver.test_nets[0].forward()
# 计算test loss
_test_loss += solver.test_nets[0].blobs['SoftmaxWithLoss1'].data
# 计算test accuracy
_accuracy += solver.test_nets[0].blobs['Accuracy1'].data
# 计算平均test loss
test_loss[it / test_interval] = _test_loss / test_iter
# 计算平均test accuracy
test_acc[it / test_interval] = _accuracy / test_iter
_test_loss = 0
_accuracy = 0 # 绘制train loss、test loss和accuracy曲线
print '\nplot the train loss and test accuracy\n'
_, ax1 = plt.subplots()
ax2 = ax1.twinx() # train loss -> 绿色
ax1.plot(display * arange(len(train_loss)), train_loss, 'g')
# test loss -> 黄色
ax1.plot(test_interval * arange(len(test_loss)), test_loss, 'y')
# test accuracy -> 红色
ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r') ax1.set_xlabel('iteration')
ax1.set_ylabel('loss')
ax2.set_ylabel('accuracy')
plt.show()

caffe Python API 之可视化的更多相关文章

  1. caffe Python API 之中值转换

    # 编写一个函数,将二进制的均值转换为python的均值 def convert_mean(binMean,npyMean): blob = caffe.proto.caffe_pb2.BlobPro ...

  2. caffe Python API 之激活函数ReLU

    import sys import os sys.path.append("/projects/caffe-ssd/python") import caffe net = caff ...

  3. caffe Python API 之 数据输入层(Data,ImageData,HDF5Data)

    import sys sys.path.append('/projects/caffe-ssd/python') import caffe4 net = caffe.NetSpec() 一.Image ...

  4. caffe Python API 之BatchNormal

    net.bn = caffe.layers.BatchNorm( net.conv1, batch_norm_param=dict( moving_average_fraction=0.90, #滑动 ...

  5. caffe Python API 之上卷积层(Deconvolution)

    对于convolution: output = (input + 2 * p  - k)  / s + 1; 对于deconvolution: output = (input - 1) * s + k ...

  6. caffe Python API 之Inference

    #以SSD的检测测试为例 def detetion(image_dir,weight,deploy,resolution=300): caffe.set_mode_gpu() net = caffe. ...

  7. caffe Python API 之图片预处理

    # 设定图片的shape格式为网络data层格式 transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) ...

  8. caffe Python API 之Model训练

    # 训练设置 # 使用GPU caffe.set_device(gpu_id) # 若不设置,默认为0 caffe.set_mode_gpu() # 使用CPU caffe.set_mode_cpu( ...

  9. caffe Python API 之Solver定义

    from caffe.proto import caffe_pb2 s = caffe_pb2.SolverParameter() path='/home/xxx/data/' solver_file ...

随机推荐

  1. liunx less 命令

    1.命令格式: less [参数]  文件 2.命令功能: less 与 more 类似,但使用 less 可以随意浏览文件,而 more 仅能向前移动,却不能向后移动,而且 less 在查看之前不会 ...

  2. (转)修改Android 的framework层后,重新编译

    1.下面方法适合真机:下载android源码,然后编译你修改的framwork的代码,会生成framework.jar,然后push到system/framework目录下,重启机器!ok 2,下面方 ...

  3. 【比赛】HNOI2018 毒瘤

    虚树+dp 直接看zlttttt的强大题解 zlttttt的题解看这里 #include<bits/stdc++.h> #define ui unsigned int #define ll ...

  4. Implement Queue by Two Stacks

    As the title described, you should only use two stacks to implement a queue's actions. The queue sho ...

  5. Zend Hash table 详解--转

    原文地址:http://www.phppan.com/2009/12/zend-hashtable/ 在PHP的Zend引擎中,有一个数据结构非常重要,它无处不在,是PHP数据存储的核心,各种常量.变 ...

  6. 【loj2461】【2018集训队互测Day 1】完美的队列

    #2461. 「2018 集训队互测 Day 1」完美的队列 传送门: https://loj.ac/problem/2461 题解: 直接做可能一次操作加入队列同时会弹出很多数字,无法维护:一个操作 ...

  7. Codeforces Round #404 (Div. 2)A B C二分

    A. Anton and Polyhedrons time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  8. jquery动态添加的元素绑定的事件不生效的问题

    我们可以通过 $(document).on('click', '#xxx', callback) 这种形式解决. 原因,一般情况下,我们是通过 $('#xxx').click(callback) 这种 ...

  9. springMVC参数的获取区别

    在springMVC中我们一般使用注解的形式来完成web项目,但是如果不明白springmvc的对于不同注解的应用场景就会很容易犯错误 1.什么是restful形式: 什么是RESTful restf ...

  10. hibernate中evict()和clear()的区别

    session.evict(obj):会把指定的缓冲对象进行清除: session.clear():把缓冲区内的全部对象清除,但不包括操作中的对象. hibernate执行的顺序如下: (1)生成一个 ...