Sparse coding with a precomputed dictionary
as
plt
import
numpy
as
np
from
sklearn.decomposition
import
def
ricker_function
(
resolution
,
center
,
width
):
"""Discrete sub-sampled Ricker (Mexican hat) wavelet"""
x
=
(
0
,
resolution
-
1
,
resolution
)
x
=
(
(
2
/
(
(
3
*
width
)
*
**
0.25
))
*
(
1
-
(
x
-
center
)
**
2
/
width
**
2
)
*
(
-
((
x
-
center
)
**
2
)
/
(
2
*
width
**
2
))
)
return
x
def
ricker_matrix
(
width
,
resolution
,
n_components
):
"""Dictionary of Ricker (Mexican hat) wavelets"""
centers
=
(
0
,
resolution
-
1
,
n_components
)
D
=
((
n_components
,
resolution
))
for
i
,
center
in
enumerate
(
centers
):
D
[
i
]
=
ricker_function
(
resolution
,
center
,
width
)
D
/=
(
(
D
**
2
,
axis
=
1
))[:,
]
return
D
resolution
=
1024
subsampling
=
3
width
=
100
n_components
=
resolution
//
subsampling
D_fixed
=
ricker_matrix
(
width
=
width
,
resolution
=
resolution
,
n_components
=
n_components
)
D_multi
=
[
tuple
(
ricker_matrix
(
width
=
w
,
resolution
=
resolution
,
n_components
=
n_components
//
5
)
for
w
in
(
10
,
50
,
100
,
500
,
1000
)
)
]
y
=
(
0
,
resolution
-
1
,
resolution
)
first_quarter
=
y
<
resolution
/
4
y
[
first_quarter
]
=
3.0
y
[
(
first_quarter
)]
=
-
1.0
estimators
=
[
(
"OMP"
,
"omp"
,
None
,
15
,
"navy"
),
(
"Lasso"
,
"lasso_lars"
,
2
,
None
,
"turquoise"
),
]
lw
=
2
(
figsize
=
(
13
,
6
))
for
subplot
,
(
D
,
title
)
in
enumerate
(
zip
((
D_fixed
,
D_multi
),
(
"fixed width"
,
"multiple widths"
))
):
(
1
,
2
,
subplot
+
1
)
(
"Sparse coding against
%s
dictionary"
%
title
)
(
y
,
lw
=
lw
,
linestyle
=
"--"
,
label
=
"Original signal"
)
for
title
,
algo
,
alpha
,
n_nonzero
,
color
in
estimators
:
coder
=
(
dictionary
=
D
,
transform_n_nonzero_coefs
=
n_nonzero
,
transform_alpha
=
alpha
,
transform_algorithm
=
algo
,
)
x
=
coder
.
transform
(
y
.
reshape
(
1
,
-
1
))
density
=
len
(
(
x
))
x
=
(
(
x
,
D
))
squared_error
=
((
y
-
x
)
**
2
)
(
x
,
color
=
color
,
lw
=
lw
,
label
=
"
%s
:
%s
nonzero coefs,
\n
%.2f
error"
%
(
title
,
density
,
squared_error
),
)
coder
=
(
dictionary
=
D
,
transform_algorithm
=
"threshold"
,
transform_alpha
=
20
)
x
=
coder
.
transform
(
y
.
reshape
(
1
,
-
1
))
_
,
idx
=
(
x
!=
0
)
.
nonzero
()
x
[
0
,
idx
],
_
,
_
,
_
=
(
D
[
idx
,
:]
.
T
,
y
,
rcond
=
None
)
x
=
(
(
x
,
D
))
squared_error
=
((
y
-
x
)
**
2
)
(
x
,
color
=
"darkorange"
,
lw
=
lw
,
label
=
"Thresholding w/ debiasing:
\n
%d
nonzero coefs,
%.2f
error"
%
(
len
(
idx
),
squared_error
),
)
(
"tight"
)
(
shadow
=
False
,
loc
=
"best"
)
(
0.04
,
0.07
,
0.97
,
0.90
,
0.09
,
0.2
)
()
Total running time of the script: (0 minutes 0.286 seconds)
Related examples