File size: 1,526 Bytes
6827b7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import streamlit as st
import numpy as np
from sklearn.decomposition import DictionaryLearning
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt

# Title of the app
st.title('Dictionary Learning Demo with Streamlit')

# Description
st.write('''
    This application demonstrates the concept of Dictionary Learning using the scikit-learn library.
    Dictionary learning aims to find a sparse representation of the data in the form of a dictionary and a sparse matrix.
''')

# Load dataset
digits = load_digits()
data = digits.data

# Display a sample image from the dataset
st.write("Sample image from the dataset:")
sample_index = 0
sample_image = data[sample_index].reshape(8, 8)
plt.imshow(sample_image, cmap='gray')
st.pyplot(plt)

# Get user input for the number of dictionary components
n_components = st.slider('Number of dictionary components', 1, 64, 32)

# Perform dictionary learning
dl = DictionaryLearning(n_components=n_components, transform_algorithm='lasso_lars', random_state=0)
X_transformed = dl.fit_transform(data)
dictionary = dl.components_

# Display the learned dictionary components
st.write("Learned dictionary components:")
fig, axes = plt.subplots(4, 8, figsize=(8, 4))
for i, ax in enumerate(axes.ravel()):
    if i < n_components:
        ax.imshow(dictionary[i].reshape(8, 8), cmap='gray')
        ax.axis('off')
st.pyplot(fig)

# Display sparsity of the transformed data
sparsity = np.mean(X_transformed == 0)
st.write(f'Sparsity of the transformed data: {sparsity:.2f}')