awacke1's picture
Create app.py
6827b7d verified
raw
history blame
1.53 kB
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}')