可视化自编码器,可视化的是
要学习的参数
W1
。
1:稀疏自编码器
Step1:在sampleIMAGES.m文件中获取生成训练集的代码,其中tic和toc是用来记时用的。
- tic
- image_size=size(IMAGES);
- i=randi(image_size(1)-patchsize+1,1,numpatches); %产生1*10000个随机数 范围在[1,image_size(1)-patchsize+1]之间
- j=randi(image_size(2)-patchsize+1,1,numpatches);
- k=randi(image_size(3),1,numpatches); % 随机的选取图片 10000次
- for num=1:numpatches
- patches(:,num)=reshape(IMAGES(i(num):i(num)+patchsize-1,j(num):j(num)+patchsize-1,k(num)),1,patchsize*patchsize);
- end
- toc
Step2:在sparseAutoencoderCost.m文件中完成前向传播和后向传播等相关代码
- %1.forward propagation
- data_size=size(data); % [64, 10000]
- active_value2=repmat(b1,1,data_size(2)); % 将b1扩展10000列 25*10000
- active_value3=repmat(b2,1,data_size(2)); % 将b2扩展10000列 64*10000
- active_value2=sigmoid(W1*data+active_value2); %隐结点的值 矩阵表示所有的样本 25*10000 一列表示一个样本 hidden
- active_value3=sigmoid(W2*active_value2+active_value3); %输出结点的值 矩阵表示所有的样本 64*10000 一列表示一个样本 output
- %2.computing error term and cost
- ave_square=sum(sum((active_value3-data).^2)./2)/data_size(2); %cost第一项 最小平方和
- weight_decay=lambda/2*(sum(sum(W1.^2))+sum(sum(W2.^2))); %cost第二项 所有参数的平方和 贝叶斯学派
- p_real=sum(active_value2,2)./data_size(2); % 稀疏惩罚项中的估计p 为25维
- p_para=repmat(sparsityParam,hiddenSize,1); %稀疏化参数
- sparsity=beta.*sum(p_para.*log(p_para./p_real)+(1-p_para).*log((1-p_para)./(1-p_real))); %KL diversion
- cost=ave_square+weight_decay+sparsity; % 最终的cost function
- delta3=(active_value3-data).*(active_value3).*(1-active_value3); % 为error 是64*10000 矩阵表示所有的样本,每一列表示一个样本
- average_sparsity=repmat(sum(active_value2,2)./data_size(2),1,data_size(2)); %求error中的稀疏项
- default_sparsity=repmat(sparsityParam,hiddenSize,data_size(2)); %稀疏化参数
- sparsity_penalty=beta.*(-(default_sparsity./average_sparsity)+((1-default_sparsity)./(1-average_sparsity
Step3:梯度检验
- EPSILON=0.0001;
- for i=1:size(theta)
- theta_plus=theta;
- theta_minu=theta;
- theta_plus(i)=theta_plus(i)+EPSILON;
- theta_minu(i)=theta_minu(i)-EPSILON;
- numgrad(i)=(J(theta_plus)-J(theta_minu))/(2*EPSILON);
- end
Step4:可视化,训练train.m的时候,要将相关梯度校验相关代码去掉,因为这部分代码比较耗时间。
2:矢量化编程实现
这个只需要在以上的代码中略做修改即可。
Step1:首先将参数设置为
- visibleSize = 28*28; % number of input units
- hiddenSize = 196; % number of hidden units
- sparsityParam = 0.1; % desired average activation of the hidden units.
- % (This was denoted by the Greek alphabet rho, which looks like a lower-case "p",
- % in the lecture notes).
- lambda = 3e-3; % weight decay parameter
- beta = 3; % weight of sparsity penalty term
Step2:将稀疏编码器中的step1获取训练集的方式换成下面代码:
- images = loadMNISTImages('train-images.idx3-ubyte');
- display_network(images(:,1:100)); % Show the first 100 images
- patches = images(:, randi(size(images,2), 1, 10000));
这样就可以得到以下可视化的结果了: