Dictionary Learning(字典学习、稀疏表示以及其他)

.png)
.png)
- from time import time
- import matplotlib.pyplot as plt
- import numpy as np
- import scipy as sp
- from sklearn.decomposition import MiniBatchDictionaryLearning
- from sklearn.feature_extraction.image import extract_patches_2d
- from sklearn.feature_extraction.image import reconstruct_from_patches_2d
- from sklearn.utils.testing import SkipTest
- from sklearn.utils.fixes import sp_version
- if sp_version < (0, 12):
- raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
- "thus does not include the scipy.misc.face() image.")
- try:
- from scipy import misc
- face = misc.face(gray=True)
- except AttributeError:
- # Old versions of scipy have face in the top level package
- face = sp.face(gray=True)

- # Convert from uint8 representation with values between 0 and 255 to
- # a floating point representation with values between 0 and 1.
- face = face / 255.0
- # downsample for higher speed
- face = face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]
- face = face / 4.0
- height, width = face.shape
- # Distort the right half of the image
- print('Distorting image...')
- distorted = face.copy()
- distorted[:, width // 2:] += 0.075 * np.random.randn(height, width // 2)
- # Extract all reference patches from the left half of the image
- print('Extracting reference patches...')
- t0 = time()
- patch_size = (7, 7)
- data = extract_patches_2d(distorted[:, :width // 2], patch_size)
- data = data.reshape(data.shape[0], -1)
- data -= np.mean(data, axis=0)
- data /= np.std(data, axis=0)
- print('done in %.2fs.' % (time() - t0))
- print('Learning the dictionary...')
- t0 = time()
- dico = MiniBatchDictionaryLearning(n_components=100, alpha=1, n_iter=500)
- V = dico.fit(data).components_
- dt = time() - t0
- print('done in %.2fs.' % dt)
- plt.figure(figsize=(4.2, 4))
- for i, comp in enumerate(V[:100]):
- plt.subplot(10, 10, i + 1)
- plt.imshow(comp.reshape(patch_size), cmap=plt.cm.gray_r,
- interpolation='nearest')
- plt.xticks(())
- plt.yticks(())
- plt.suptitle('Dictionary learned from face patches\n' +
- 'Train time %.1fs on %d patches' % (dt, len(data)),
- fontsize=16)
- plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)#left, right, bottom, top, wspace, hspace

.png)
- def show_with_diff(image, reference, title):
- """Helper function to display denoising"""
- plt.figure(figsize=(5, 3.3))
- plt.subplot(1, 2, 1)
- plt.title('Image')
- plt.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray,
- interpolation='nearest')
- plt.xticks(())
- plt.yticks(())
- plt.subplot(1, 2, 2)
- difference = image - reference
- plt.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2)))
- plt.imshow(difference, vmin=-0.5, vmax=0.5, cmap=plt.cm.PuOr,
- interpolation='nearest')
- plt.xticks(())
- plt.yticks(())
- plt.suptitle(title, size=16)
- plt.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2)
- show_with_diff(distorted, face, 'Distorted image')

.png)
- print('Extracting noisy patches... ')
- t0 = time()
- data = extract_patches_2d(distorted[:, width // 2:], patch_size)
- data = data.reshape(data.shape[0], -1)
- intercept = np.mean(data, axis=0)
- data -= intercept
- print('done in %.2fs.' % (time() - t0))
- transform_algorithms = [
- ('Orthogonal Matching Pursuit\n1 atom', 'omp',
- {'transform_n_nonzero_coefs': 1}),
- ('Orthogonal Matching Pursuit\n2 atoms', 'omp',
- {'transform_n_nonzero_coefs': 2}),
- ('Least-angle regression\n5 atoms', 'lars',
- {'transform_n_nonzero_coefs': 5}),
- ('Thresholding\n alpha=0.1', 'threshold', {'transform_alpha': .1})]
- reconstructions = {}
- for title, transform_algorithm, kwargs in transform_algorithms:
- print(title + '...')
- reconstructions[title] = face.copy()
- t0 = time()
- dico.set_params(transform_algorithm=transform_algorithm, **kwargs)
- code = dico.transform(data)
- patches = np.dot(code, V)
- patches += intercept
- patches = patches.reshape(len(data), *patch_size)
- if transform_algorithm == 'threshold':
- patches -= patches.min()
- patches /= patches.max()
- reconstructions[title][:, width // 2:] = reconstruct_from_patches_2d(
- patches, (height, width // 2))
- dt = time() - t0
- print('done in %.2fs.' % dt)
- show_with_diff(reconstructions[title], face,
- title + ' (time: %.1fs)' % dt)
- plt.show()
.png)
.png)
.png)
.png)



Dictionary Learning(字典学习、稀疏表示以及其他)的更多相关文章
- 稀疏编码(sparse code)与字典学习(dictionary learning)
Dictionary Learning Tools for Matlab. 1. 简介 字典 D∈RN×K(其中 K>N),共有 k 个原子,x∈RN×1 在字典 D 下的表示为 w,则获取较为 ...
- 学习人工智能的第五个月[字典学习[Dictionary Learning,DL]]
摘要: 大白话解释字典学习,分享第五个月的学习过程,人生感悟,最后是自问自答. 目录: 1.字典学习(Dictionary Learning,DL) 2.学习过程 3.自问自答 内容: 1.字典学习( ...
- 字典学习(Dictionary Learning, KSVD)详解
注:字典学习也是一种数据降维的方法,这里我用到SVD的知识,对SVD不太理解的地方,可以看看这篇博客:<SVD(奇异值分解)小结 >. 1.字典学习思想 字典学习的思想应该源来实际生活中的 ...
- 字典学习(Dictionary Learning)
0 - 背景 0.0 - 为什么需要字典学习? 这里引用这个博客的一段话,我觉得可以很好的解释这个问题. 回答这个问题实际上就是要回答“稀疏字典学习 ”中的字典是怎么来的.做一个比喻,句子是人类社会最 ...
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料【转】
转自:机器学习(Machine Learning)&深度学习(Deep Learning)资料 <Brief History of Machine Learning> 介绍:这是一 ...
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料汇总 (上)
转载:http://dataunion.org/8463.html?utm_source=tuicool&utm_medium=referral <Brief History of Ma ...
- 联合CRF和字典学习的自顶向下的视觉显著性-全文解读
top-down visual saliency via joint CRF anddictionary learning 自顶向下的视觉显著性是使用目标对象的可判别表示和一个降低搜索空间的概率图来进 ...
- 论文阅读笔记(十九)【ITIP2017】:Super-Resolution Person Re-Identification With Semi-Coupled Low-Rank Discriminant Dictionary Learning
Introduction (1)问题描述: super resolution(SP)问题:Gallery是 high resolution(HR),Probe是 low resolution(LR). ...
- 论文阅读笔记(六)【TCSVT2018】:Semi-Supervised Cross-View Projection-Based Dictionary Learning for Video-Based Person Re-Identification
Introduction (1)Motivation: ① 现实场景中,给所有视频进行标记是一项繁琐和高成本的工作,而且随着监控相机的记录,视频信息会快速增多,因此需要采用半监督学习的方式,只对一部分 ...
随机推荐
- IP变化,SVN和数据库的修改
最近公司换了运营商,将启用新的IP地址,将以前项目的端口映射处理好之外,还需要切换SVN的地址. 项目开发中有可能要修改SVN的IP地址,entries文件里面包含svn服务器的地址信息.每个文件夹都 ...
- bzoj violet系列 (2708~2725)
cbh大爷说:写博客不能弃坑. orz cbh 那我就来更新博客了. violet这个系列的题好神啊……出题人好劲啊…… ……怎么最近都在理性愉悦啊…… 另外bzoj400题纪念~ 2708: [Vi ...
- js 对数据转换成数据容量单位
function bytesToSize(value) { alert(value); alert('value'); debugger; if (value === 0) return '0 B'; ...
- C#夯实基础之多线程三:线程的优先级
一.为什么需要优先级--线程调度的问题 在现实生活中,优先级是一个很常见的现象:在火车站,如果你是孕妇,你是可以走进站中的专门绿色通道的,可以提前上火车以免拥挤:火警119匪警110出警的时候,都是人 ...
- 设计模式--建造者模式Builder(创建型)
一.首先看建造者模式的UML图: 二.再来看一个建造者模式的例子 class Builder { public: virtual void BuildHead() {} virtual void Bu ...
- Bootstrap.css 中请求googleapis.com/css?family 备忘录
问题描述: Web中引入bootstrap.css中头部有访问Google服务器的请求 @import url("//fonts.googleapis.com/css?family=Open ...
- getAttribute、setAttribute、removeAttribute
1.函数语法 elementNode.attributes:属性返回包含被选节点属性的 NamedNodeMap. elementNode.getAttribute(name):方法通过名称获取属性的 ...
- C# Stream
转载:C# 温故而知新:Stream篇(一.二) http://www.cnblogs.com/JimmyZheng/archive/2012/03/17/2402814.html#no2 http: ...
- gulp整理
gulp基于node 1.全局安装gulp: $ npm install --global gulp 2.前往项目目录,然后安装作为项目的开发依赖(devDependencies): $ npm in ...
- vsftpd:500 OOPS: vsftpd: refusing to run with writable root inside chroot ()错误的解决方法
---恢复内容开始--- 最近在安装了vsftpd后 添加了虚拟账户后 新建用户 为新用户创立独立的工作目录 因为虚拟用户在工作目录需要上传文件 所以必须拥有此目录的W权限,但每当给此目录加上W权限后 ...