Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • ko11920/thesiscodeimplementation
1 result
Show changes
Commits on Source (3)
Showing
with 176417 additions and 74 deletions
......@@ -5,90 +5,58 @@ This is the code implementation of my Bsc Thesis, which has topic of "Unsupervis
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
## Installation Prerequisites
Before you get started,
```bash
1. System should have IDE or text editor
2. Python version 3.9.0
3. PIP
```
cd existing_repo
git remote add origin https://mygit.th-deg.de/ko11920/thesiscodeimplementation.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://mygit.th-deg.de/ko11920/thesiscodeimplementation/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
# Set-up an Environment:
***
Clustering-Tool is built with Python and Streamlit.
For the installation of a local development is described below.
# Editing this README
### For a virtual environment,
Independent of which package management tool you use, it is recommended that commands on this page are
run in a virtual environment. By doing so, it ensures that the dependencies added for Streamlit will not
impact other Python projects you are working on.
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
Tools use for environment management:
- [conda](https://www.anaconda.com/products/distribution)
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## 1. Clone repository to a destination folder
```bash
git clone https://mygit.th-deg.de/kv14423/clustering-tool.git
```
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Set-up
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
```bash
conda create --name <VenvEnvName> python==3.9.0 -y
```
```bash
conda activate <VenvEnvName>
```
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
```bash
pip install -r requirements.txt
```
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
## Code Structure
For the replication of the results, you need to run those python files.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
Firstly to run those algorithms defined in the thesis and plots the CVI metrics, run the following pythn files as follow:
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## 1. Run fine_tune_hyperparameter.py
After the execution of the script, a new folder is created where CVI metrics of those datasets is created named as <b>cvi_results_of_clustering
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## 2. Run select_optimal_parameters.py
Using the cvi score of clustering algorithms for each dataset of <b>cvi_results_of_clustering folder, run this script and new folder for composite score is created called <b>composite_score_results which takes the best parameters from the cvi_results.
## License
For open source projects, say how it is licensed.
## 3. Run optimal_hyperparameter_plot.py
This script plots the no of cluster for those cvi indices based on the composite score.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
## 4. Run plot_for_all_cvi_from_all_data.py
This script is used to plot the five CVI indices for the clusterd of whole dataset that shows the cvi-score for all the algorithms used, which represent the best algorithms according to cvi.
\ No newline at end of file
Screenshot from 2025-03-03 14-19-33.png

912 KiB

......@@ -706,7 +706,7 @@ def visualize_features_heatmap(daily_aggregates):
# Example Usage
if __name__ == "__main__":
# Step 1: Load the dataset
data = pd.read_csv("/home/jvaldes/Desktop/krishna-thesis/thesiscodeimplementation/data/EFH (1).csv") # Replace with your dataset file
data = pd.read_csv("/home/jvaldes/Desktop/krishna-thesis/thesiscodeimplementation/data/eth_data/EFH (8).csv") # Replace with your dataset file
# Process the data to get daily mean values
daily_mean_df = process_daily_mean_power(data)
......
clust_0_data_gen.png

44.2 KiB

clust_1_gen_data.png

41.1 KiB

clust_2_gen_data.png

40.1 KiB

clust_3_gen_data.png

43.1 KiB

clust_4_gen_data.png

37.7 KiB

Silhouette Score,Davies-Bouldin Score,Calinski-Harabasz Score,Dunn Index,COP Index,Score Function
0.23010091440535346,0.8125262754129975,75.67886360829836,0.00191514031834882,0.010523960350357313,0.08340997077066392
0.3104714677604624,0.852058991814046,233.13824672633373,0.012709898306111338,0.007268193467649197,0.04207614520369935
clusters_plot.png

175 KiB

###########################################
########### Imports ###########
###########################################
from re import S
import math
import streamlit as st
import matplotlib as plt
import pandas as pd
import textwrap
import statsmodels.formula.api as smf
import statsmodels.tsa.api as smt
import statsmodels.api as sm
import scipy.stats as scs
import numba
import numpy as np
import matplotlib.cm as cm
##### Plotly ######
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
import plotly.graph_objects as go
import chart_studio
from plotly import tools
from plotly.subplots import make_subplots
import time #from datetime import datetime
import datetime
from scipy.fftpack import rfft
from scipy.stats import boxcox
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.metrics import davies_bouldin_score
from sklearn_extra.cluster import KMedoids
from sklearn.metrics import calinski_harabasz_score
from scipy.cluster.hierarchy import single, complete, average, ward, dendrogram, linkage
from sklearn.metrics.cluster import contingency_matrix
from sklearn.manifold import TSNE
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.impute import SimpleImputer
from datetime import timedelta #from datetime import datetime
# Algorithms
from tslearn.barycenters import dtw_barycenter_averaging
from tslearn.clustering import TimeSeriesKMeans
from sktime.distances import dtw_distance
from dtaidistance import clustering, dtw
#from fcmeans import FCM
# IMplementation for pyclustering kmeans
from pyclustering.cluster.kmeans import kmeans
from pyclustering.cluster.center_initializer import random_center_initializer
from pyclustering.cluster.encoder import type_encoding
from pyclustering.cluster.encoder import cluster_encoder
from pyclustering.utils.metric import distance_metric
from pyclustering.cluster.center_initializer import kmeans_plusplus_initializer
from pyclustering.cluster.fcm import fcm
from sklearn.metrics import pairwise_distances
from validclust import cop, dunn
# Preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.cluster import contingency_matrix
from tslearn.clustering import TimeSeriesKMeans
from tslearn.preprocessing import TimeSeriesScalerMeanVariance
from netdata_pandas.data import get_data, get_chart_list
from am4894plots.plots import plot_lines, plot_lines_grid
from matplotlib.patches import Ellipse
from sklearn import preprocessing
#from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, silhouette_samples
from yellowbrick.cluster import SilhouetteVisualizer, KElbowVisualizer
from sklearn.model_selection import train_test_split
#from statsmodels.tsa.arima_model import ARIMA
import warnings # `do not disturbe` mode
warnings.filterwarnings('ignore')
###########################################
# pre-Input for the Dynamic clustering #
diff = False # take diffs of the data or not
preprocessing_meanvar = False # True to use TimeSeriesScalerMeanVariance preprocessing
preprocessing_fft = False # True if you want to do the clustering based on fft transformation of X
preprocessing_sqrt = True
preprocessing_log = False
norm = True # normalize the data to 0-1 range
###########################################
####### DEF for null values #####
def null_values(df):
null_test = (df.isnull().sum(axis=0) / len(df)).sort_values(ascending=False).index
null_data_test = pd.concat([
df.isnull().sum(axis=0),
(df.isnull().sum(axis=0) / len(df)).sort_values(ascending=False),
df.loc[:, df.columns.isin(list(null_test))].dtypes], axis=1)
null_data_test = null_data_test.rename(columns={0: '# null',
1: '% null',
2: 'type'}).sort_values(ascending=False, by='% null')
null_data_test = null_data_test[null_data_test["# null"] != 0]
return null_data_test
def type(df):
return pd.DataFrame(df.dtypes, columns=['Type'])
def preprocessing_meanvar(df):
X = TimeSeriesScalerMeanVariance().fit_transform(X)
df = pd.DataFrame(X.reshape(df.shape), columns=df.columns, index=df.index)
return df
def purity_score(y_true, y_pred):
# compute contingency matrix (also called confusion matrix)
confusion_matrix = contingency_matrix(y_true, y_pred)
# return purity
return np.sum(np.amax(confusion_matrix, axis=0)) / np.sum(confusion_matrix)
def read_csv_and_auto_update_time_interval(uploaded_file):
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
df = data.copy()
# Convert the 'Time' column to datetime
if 'Time' in df:
df['Time'] = pd.to_datetime(df['Time'])
# If 'Date' column exists, use it; otherwise, create it
if 'Date' not in df:
df['Date'] = df['Time'].dt.date if 'Time' in df else pd.to_datetime("now").date()
# Infer the time interval from the 'Time' or 'Date' column
if 'Time' in df:
time_interval = (df['Time'].diff().mean()).seconds
else:
# If only 'Date' is present, assume a 1-day interval
time_interval = 86400 # 1 day in seconds
time_interval_str = f"{time_interval // 60}T"
# Calculate the start date and end date based on the inferred time interval
start_date = df['Time'].min() if 'Time' in df else df['Date'].min()
end_date = df['Time'].max() if 'Time' in df else df['Date'].max()
# Use the inferred time interval to generate the date range
date_range = pd.date_range(start=start_date, end=end_date, freq=time_interval_str)
# Update the 'Date' column with the new date range
if 'Date' in df:
df['Date'] = date_range
# Extract time-related features
df['Hour'] = df['Date'].dt.hour
df['Days'] = df['Date'].dt.dayofyear
df['Weekday'] = df['Date'].dt.weekday
df['Month'] = pd.DatetimeIndex(df['Date']).month
return df, time_interval_str
st.subheader('Please upload your .csv file to continue..!')
#@st.cache_resource
def app():
#st.sidebar.title('Clustering-Tool')
activities = ["1. Exploratory Data Analysis", "2. Time Series Analysis", "3. Clustering", "4. Plotting and Visualization"]
choice = st.sidebar.selectbox("Select Activity", activities)
# Upload file way
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
global data, df, df1 # global declariation
###########################################
# Exploratory Data Analysis EDA #
###########################################
#defining all_columns as global
if uploaded_file is not None and choice == "1. Exploratory Data Analysis":
df, time_interval = read_csv_and_auto_update_time_interval(uploaded_file)
#st.write(f"Data with inferred time interval ({time_interval}):")
#st.dataframe(df)
#print(data)
st.subheader(choice)
# Show row dataset
if st.checkbox("Show Dataset"):
rows = st.number_input("Number of rows", 10, len(data))
st.dataframe(data.head(rows))
# New data set
if st.checkbox("Show New Dataset"):
n_rows = st.number_input("Number of new rows", 10, len(df))
st.dataframe(df.head(n_rows))
# Show columns
if st.checkbox("Columns"):
st.write(df.columns)
# Shows Data types
if st.checkbox("Column types"):
st.write(df.dtypes.astype(str))
# Show Shape
if st.checkbox("Shape of Dataset"):
data_dim = st.radio("Show by", ("Rows", "Columns", "Shape"))
if data_dim == "Columns":
st.text("Number of Columns: ")
st.write(df.shape[1])
elif data_dim == "Rows":
st.text("Number of Rows: ")
st.write(df.shape[0])
else:
st.write(df.shape)
# Check null values in dataset
if st.checkbox("Check null values"):
nvalues = null_values(df)
st.write(nvalues)
# Show Data summary
if st.checkbox("Show Data Summary"):
st.text("Datatypes Summary")
st.write(df.describe())
###########################################
# Time Series Analysis #
###########################################2014
st.subheader('2. Time Series Analysis')
file_container = st.expander("Timeseries Data")
file_container.write(df)
all_cols = df.columns.tolist()
nums = df.select_dtypes(include=np.number).columns.tolist()
dates = list(filter(lambda x: 'date' in x.lower(), df.columns))
no_dates = list(filter(lambda x: 'date' not in x.lower(), df.columns))
valu_col = st.selectbox(
'1. Pick the VALUE column for PLOTS in your data?',(nums),1)
#df.index
#)
dat_col = st.selectbox(
'2. Pick the date column in your data?',
(dates), 0)
piv_col = st.selectbox(
'3. Pick the PIVOT column in your data?',
(df.columns), df.columns.get_loc('Hour')) # Set default to 'Hour'
dat_plt = st.selectbox(
'4. Pick the TIME for PLOTS in your data?',
('YEAR', 'YEAR-MONTH', 'Days', 'Hour', 'Month', 'Weekday'), 3) # Set default to 'Month'
filt_col = st.selectbox(
'5. Pick the filter column in your data?',
(no_dates), no_dates.index('Weekday')) # Set default to 'Weekday'
piks = df[filt_col].unique()
filtrs = st.multiselect('6. Select values to be included',piks,piks)
df = df[df[filt_col].isin(filtrs)]
df['YEAR'] = pd.to_datetime(df[dat_col]).dt.year
df['YEAR-MONTH'] = pd.to_datetime(df[dat_col]).dt.to_period('M')
df1 = pd.pivot_table(df,
values=valu_col,
#valu_col,
index=dat_plt,
columns=piv_col)
df1.columns.name = None
df1 = df1.reset_index()
df1.set_index(dat_plt, inplace=True)
df1.index = df1.index.to_series().astype(str)
se = df1.sum()
star_date, en_date = st.select_slider(
'Select the date range',
options=df1.index, value=(df1.index[0], df1.index[-1])
)
st.write('Selected values are', star_date, ' and ', en_date)
if st.button('Series PLot from selection'):
fig = px.line(df1[star_date:en_date]
)
st.plotly_chart(fig)
if st.button('Get the pivot table from your selction and continue with Clustering'):
st.write('Pivot Table from your selection')
st.write(df1[star_date:en_date])# genertaes the pivot table from the selection
# writing data frame to a CSV file
c_u = df1.to_csv()
col1, col2, col3 = st.columns(3)
with col2:
pass
with col3:
pass
with col1:
center_button = st.download_button(
label="Save PIVOT",
data=c_u,
file_name='pivot.csv',
mime='text/csv',
)
###########################################
# Plotting and Visualization #
###########################################
elif uploaded_file is not None and choice == "4. Plotting and Visualization":
st.subheader(choice)
all_columns = df.columns.tolist()
#all_cols = df.columns.tolist()
num = df.select_dtypes(include=np.number).columns.tolist()
no_date = list(filter(lambda x: 'date' not in x.lower(), df.columns))
type_of_plot = st.selectbox("Select Type of Plot",
["line", "scatter", "bar", "correlation", "distribution"])
if type_of_plot == "line":
line_y = st.selectbox("Select the value col", (num), 0)
line_x = st.selectbox("Select a column for X Axis", all_columns)
fil_coll = st.selectbox("Pick the filter feature in data?",
(no_date), 0)
if st.button('Line Chart'):
fig = px.line(df, x=line_x, y=line_y, color=fil_coll, markers=True)
st.plotly_chart(fig)
elif type_of_plot == "bar":
bar_y = st.selectbox("Select the value col", (num), 0)
bar_x = st.selectbox("Select a column for X Axis", all_columns)
fils_coll = st.selectbox("Pick the filter feature for Bar",
(no_date), 0)
if st.button('Bar Chart'):
fig = px.bar(df, x=bar_x, y=bar_y, color=fils_coll)
st.plotly_chart(fig)
elif type_of_plot == "correlation":
cor_coll = st.selectbox("Pick the filter feature for Corelation",
(no_date), 0)
if st.button('Correlation plot'):
fig = px.scatter_matrix(df,
color=cor_coll,
)
st.plotly_chart(fig)
elif type_of_plot == "scatter":
st.write("Scatter Plot")
scatter_y = st.selectbox("Select the value col", (num), 0)
scatter_x = st.selectbox("Select a column for X Axis", all_columns)
fil_col = st.selectbox("Pick the filter feature in your data?",
(no_date), 0)
if st.button('Scatter plot'):
fig = px.scatter(df,
x= scatter_x,
y= scatter_y,
color= fil_col,
)
st.plotly_chart(fig)
elif type_of_plot == "distribution":
hist_y = st.selectbox("Select the value col", (num), 0)
hist_x = st.selectbox("Select a column for X Axis", all_columns)
hist_col = st.selectbox("Pick the filter feature in your data?",
(no_date), 0)
if st.button('Distribution Chart'):
fig = px.histogram(df, x=hist_x, y=hist_y, color=hist_col, marginal="box",
hover_data=df[all_columns])
st.plotly_chart(fig)
###########################################
# Clustering #
###########################################
elif uploaded_file is not None and choice == "3. Clustering":
st.subheader(choice)
st.sidebar.subheader('Clustering Parameters')
# New data set
dataf = df1.copy()
file_container = st.expander("Data Set")
file_container.write(dataf)
all_column = df.columns.tolist()
nums = df.select_dtypes(include=np.number).columns.tolist()
non_date = list(filter(lambda x: 'date' not in x.lower(), df.columns))
if st.checkbox("Plot the Pre-Cluster data set"):
fig = px.scatter(df1,
)
st.plotly_chart(fig)
Xx = df1.copy()
# Check for and handle missing values
if Xx.isna().sum().sum() > 0:
imputer = SimpleImputer(strategy='mean')
Xx = imputer.fit_transform(Xx)
# Scale the data
scaler = MinMaxScaler()
Xx = scaler.fit_transform(Xx)
n_clusters = st.sidebar.number_input("Choose the number of Clusters", 2, 50, step=2, key='no_of_clusters')
number = st.sidebar.number_input('Random Seed', min_value=10, step=15)
kmeans= KMeans(n_clusters)
kmeans.fit(Xx)
clustered_data = df1.copy() # Create a new DataFrame
clustered_data['cluster_pred'] = kmeans.fit_predict(Xx) # Add the 'cluster_pred' column
x_array = np.array(df1)
scaler = MinMaxScaler()
x_scaled = scaler.fit_transform(x_array)
###########################################
### Silhouette Plot ###
###########################################
if st.checkbox("Plot Silhouette score"):
st.write("SIl plot ")
# Now check silhouette coefficient
figures = []
r_n_clus=range(2, 12)
for n_clusters in r_n_clus:
# Create a subplot with 1 row and 2 columns
fig = tools.make_subplots(rows=1, cols=2,
print_grid=False,
subplot_titles=('The silhouette plot for the different clusters.',
'With visualization of the clustered data.'))
# SIl range among [-0.1, 1]
fig['layout']['xaxis1'].update(title='The SIL coefficient values',
range=[-0.1, 1])
# Let's print every clusters, to delimit it clearly.
fig['layout']['yaxis1'].update(title='Cluster label',
showticklabels=False,
range=[0, len(x_array) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
cl_er = KMeans(n_clusters=n_clusters, random_state=number)
# Impute missing values
imputer = SimpleImputer(strategy='mean')
x_array = imputer.fit_transform(x_array)
# Scale the data
scaler = MinMaxScaler()
x_array = scaler.fit_transform(x_array)
cl_lab = cl_er.fit_predict(x_array)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
silhouette_avg = silhouette_score(x_array, cl_lab)
#print("For n_clusters =", n_clusters,
# "The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sam_sil = silhouette_samples(x_array, cl_lab)
y_low = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
n_sil_values = sam_sil[cl_lab == i]
n_sil_values.sort()
dm_cl_i = n_sil_values.shape[0]
y_up = y_low + dm_cl_i
d_area = go.Line( y=np.arange(y_low, y_up),
x=n_sil_values,
mode='lines',
showlegend=True,
#color='dodgerblue',
line=dict(width=0.5, color='dodgerblue'),
fill='tozerox')
fig.append_trace(d_area, 1, 1)
# Compute the new y_lower for next plot
y_low = y_up + 10 # 10 for the 0 samples
# The vertical line for average silhouette score of all the values
a_line = go.Line(x=[silhouette_avg],
#y=[0, 10],
showlegend=True,
mode='lines',
line=dict(color="red", dash='dash',
width=1))
fig.append_trace(a_line, 1, 1)
# 2nd Plot showing the actual clusters formed
clr = cm.nipy_spectral(cl_lab.astype(float) / n_clusters)
cfig = go.Line(
x=x_array[:, 0],
y=x_array[:, 1],
showlegend=True,
mode='markers',
marker=dict(color=clr,
size=4)
)
fig.append_trace(cfig, 1, 2)
# Labeling the clusters
cen = cl_er.cluster_centers_
# circles at cluster centers
cen = go.Line(x=cen[:, 0],
y=cen[:, 1],
showlegend=True,
mode='markers',
marker=dict(color='green', size=10,
line=dict(color='black',
width=1))
)
fig.append_trace(cen, 1, 2)
fig['layout']['xaxis2'].update(title='Feature space for the 1st feature',
zeroline=False)
fig['layout']['yaxis2'].update(title='Feature space for the 2nd feature',
zeroline=False)
fig['layout'].update(title="Silhouette analysis for KMeans clustering "
"with n_clusters = %d" % n_clusters)
figures.append(fig)
st.plotly_chart(fig)
#st.checkbox("Number of cluster with average of Silhouette Score")
sil_con = st.expander("For no_cluster with avg. of Sil Score")
st.write("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
###########################################
### Dynamic Clustering ###
###########################################
if st.sidebar.checkbox("Dynamic Clustering"):
st.subheader("Dynamic Clusterng ")
mod_l = ['Time Series K-Means', 'hierarchical', 'DBA', 'KMedoids']
mod_choice = st.sidebar.selectbox("Select model", mod_l)
"""centr = ['mean','min','max','sum', 'median']
# "mean", "median", "shape", "dba", "pam", "sdtw_cent"]
centr_choice = st.sidebar.selectbox("Select cenroid", centr)"""
## Dynamic Clustering
norm = True # data to 0-1 range normalizing
preprocessing_meanvar = False # Set to True if use TimeSeriesScalerMeanVariance
# Fast Fourier Transform (fft) and Clustering of Time Series
# Set to True if to do the clustering based on fft transformation of X : can use in future development
preprocessing_fft = False
preprocessing_sqrt = True
preprocessing_log = False
model = mod_choice # ['Partitional', 'hierarchical', 'DBA', 'KMedoids'] # you can add DTW, soft-DTW, kshape too
min_n = 0 # only interested in clusters with min_n or more members
# Perform smoothing as specified
"""if smooth_n > 0:
if smooth_func == 'mean':
df2 = df2.rolling(smooth_n).mean().dropna(how='all')
elif smooth_func == 'min':
df2 = df2.rolling(smooth_n).min().dropna(how='all')
elif smooth_func == 'max':
df2 = df2.rolling(smooth_n).max().dropna(how='all')
elif smooth_func == 'sum':
df2 = df2.rolling(smooth_n).sum().dropna(how='all')
elif smooth_func == 'median':
df2 = df2.rolling(smooth_n).median().dropna(how='all')
else:
df2 = df2.rolling(smooth_n).mean().dropna(how='all')""" # throwing some errors
df2= df1.copy()
df2 = df2.loc[:, ~df2.columns.duplicated()]
# To drop any empty columns
df2 = df2.dropna(axis=1, how='all')
# use if necessary to try remove any N/A values and use forward fill and backward fill to
df2 = df2.ffill().bfill()
df2 = df2.fillna(df2.mean())
# do sqrt
if preprocessing_sqrt:
df2 = df2.apply(lambda col: np.sqrt(col))
# do log if set True
if preprocessing_log:
df2 = df2.apply(lambda col: np.log1p(col))
# take differences if specified
if diff:
df2 = df2.diff()
start_time = time.perf_counter()
# normalizing data once
if norm:
df2 = (df2 - df2.min()) / (df2.max() - df2.min())
# drop any empty columns that may remain
df2 = df2.dropna(axis=1, how='all')
# look at our data
#print("DF2 ",df2.shape, " shape is")
#print(df2.index.min(), df2.index.max())
df2.head()
#print("latest DF2 ", df2, " is.")
#st.write("New DF ")
#file_contai = st.expander("New DataSet")
#file_contai.write(df2)
# Handle missing values with SimpleImputer
imputer = SimpleImputer(strategy='mean')
df2 = imputer.fit_transform(df2)
# Get values to cluster on
if preprocessing_fft:
X = rfft(df2).transpose()
else:
X = df2.transpose()
iter = st.sidebar.number_input('Max Iteration', min_value=10, step=5)
n_init = st.sidebar.number_input('n init', min_value=2, step=2)
###########################################
### Clustering Models ###
###########################################
if (mod_choice == 'Time Series K-Means'):
dis = ["euclidean", "dtw", "softdtw"]
dis_choice = st.sidebar.selectbox("Select Distance measure", dis)
mod_choice = TimeSeriesKMeans(n_clusters=n_clusters, metric=dis_choice, max_iter=iter, n_init=n_init, random_state=number).fit(X)
elif (mod_choice == 'DTW'):
dis = ["euclidean", "dtw", "softdtw"]
dis_choice = st.sidebar.selectbox("Select Distance measure", dis)
mod_choice = TimeSeriesKMeans(n_clusters=n_clusters, metric=dis_choice, max_iter=iter, n_init=n_init, random_state=number).fit(X)
elif (mod_choice == 'softdtw'):
dis = ["euclidean", "dtw", "softdtw"]
dis_choice = st.sidebar.selectbox("Select Distance measure", dis)
mod_choice = TimeSeriesKMeans(n_clusters=n_clusters, metric=dis_choice, max_iter=iter, n_init=n_init, random_state=number).fit(X)
elif (mod_choice == 'hierarchical'):
dis = ["euclidean", "manhattan", "cosine"]
dis_choice = st.sidebar.selectbox("Select Affinity measure", dis)
link = ['single', 'complete', 'average', 'ward']
link_choice = st.sidebar.selectbox("Select Linkage", link)
mod_choice = AgglomerativeClustering(distance_threshold=None, n_clusters=n_clusters, affinity=dis_choice,
linkage=link_choice).fit(X)
if st.checkbox("Plot Dendrogram"):
#plots_title = ( 'The Dendrogram for %d' % link_choice )
if link_choice == 'single':
Z = linkage(X, 'single')
elif link_choice == 'complete':
Z = linkage(X, 'complete')
elif link_choice == 'average':
Z = linkage(X, 'average')
elif link_choice == 'ward':
Z = linkage(X, 'ward')
fig = ff.create_dendrogram(Z)
#fig.update_layout(color_threshold=1.5)
st.plotly_chart(fig)
elif (mod_choice == 'Fuzzy'): ## need some development
cent = ['fcm', 'fcmdd']
cent_choice = st.sidebar.selectbox("Select Centroid", cent)
#initial_centers = kmeans_plusplus_initializer(df2, 3,
# kmeans_plusplus_initializer.FARTHEST_CENTER_CANDIDATE).initialize()
mod_choice = fcm( method="Cmeans", n_clusters = n_clusters, max_iter=iter,
random_state=number, matric= 'euclidean')
#create instance of Fuzzy C-Means algorithm
fcm_instance = fcm(df2, initial_centers)
# run cluster analysis and obtain results
fcm_instance.process()
df_cluster = fcm_instance.get_clusters()
#print("FCM labels ",FCM.labels_, " this.")
#fcm_fit = mod_choice.fit(tr_set)
#mod_choice = mod_choice.centers.T
elif (mod_choice == 'DBA'):
dis = ["euclidean", "dtw", "softdtw"]
dis_choice = st.sidebar.selectbox("Select Distance measure", dis)
mod_choice = TimeSeriesKMeans(n_clusters=n_clusters, n_init=n_init, metric=dis_choice, verbose=True,
max_iter_barycenter=iter,
random_state=number).fit(X)
elif (mod_choice == 'KMedoids'):
dis = ["euclidean", "manhattan", "chebyshev", "canberra", "minkowski", "cosine"]
dis_choice = st.sidebar.selectbox("Select Distance measure", dis)
mod_choice = KMedoids(n_clusters=n_clusters, metric=dis_choice, method='pam', random_state=number).fit(X)
#print(len(set(mod_choice.labels_)))
#print("Model labels are ",mod_choice.labels_, " is this.")
silhouette_avrg = silhouette_score(X, mod_choice.labels_)
#print("Latest Silhouette ",round(silhouette_avrg,2), " average is.")
df2 = pd.DataFrame(df2)
# Generate a darafreame along with metrics and their cluster labels
cl_df = pd.DataFrame(list(zip(df2.columns, mod_choice.labels_)), columns=['metric', 'cluster'])
# Generating helper dictionaries and lists
cl_met = cl_df.groupby(['cluster'])['metric'].apply(lambda x: [x for x in x]).to_dict()
cl_count = cl_df['cluster'].value_counts().to_dict()
a_clust = [cluster for cluster in cl_count]
drp_clust = [cluster for cluster in cl_count if cl_count[cluster] < min_n]
list_clust = [cluster for cluster in cl_count if cl_count[cluster] >= min_n]
clst_final= np.array(list_clust)
if st.checkbox("Data frame WIth Metric and CLuster "):
#st.write("DTW plot ")
ff_contai = st.expander("DataFrame Metric and CLuster")
ff_contai.write(cl_df)
# writing data frame to a CSV file
cl_u = cl_df.to_csv()
col1, col2, col3 = st.columns(3)
with col1:
pass
with col3:
pass
with col2:
center_button = st.download_button(
label="Save DataFrame",
data=cl_u,
file_name='df_met_clust.csv',
mime='text/csv',
)
#print(cl_df)
data2 = np.array([mod_choice.labels_])
#print(data2)
d_cl_qua = {}
for clst_i in a_clust:
cr_x = df2[cl_met[clst_i]].corr().abs().values
cr_x_mean = round(cr_x[np.triu_indices(cr_x.shape[0], 1)].mean(), 2)
d_cl_qua[clst_i] = cr_x_mean
# get quality score for each cluster
#if st.checkbox("View CVI's"):
#clst_eqal_choice == 'sil'
silhouette_scores = silhouette_samples(X, mod_choice.labels_)
cl_df_sil = pd.DataFrame(
list(zip(mod_choice.labels_, silhouette_scores)),
columns=['cluster', 'silhouette_score'])
cl_df_sil = cl_df_sil.groupby(['cluster']).max()
# print("Cluster Sil ",cl_df_sil, " score.")
d_cl_qua = cl_df_sil.to_dict()['silhouette_score']
# print("1. SIlhouette index ", silhouette_avrg, " is.")
#print("2. Latest Silhouette ", round(silhouette_avrg, 2), " average is.")
# build cluster level df with some cluster metadata
cl_df_met = pd.DataFrame.from_dict(cl_count, orient='index', columns=['n'])
cl_df_met.index.names = ['cluster']
#d_cl_qua = silhouette_avrg.to_dict()['silhouette_score']
cl_df_met['quality_score'] = cl_df_met.index.map(d_cl_qua)
cl_df_met = cl_df_met.sort_values('quality_score', ascending=False)
#cl_df_met.head()
#print(cl_df_met)
if st.checkbox("CLuster with quality score"):
f_contai = st.expander("CLuster and its quality score")
f_contai.write(cl_df_met)
# writing data frame to a CSV file
cl_cu = cl_df_met.to_csv()
col1, col2, col3 = st.columns(3)
with col1:
pass
with col3:
pass
with col2:
center_button = st.download_button(
label="Save quality score",
data=cl_cu,
file_name='quality_score.csv',
mime='text/csv',
)
# Plotting every clusters
if st.checkbox("Plot each cluster"):
for clst_i, row in cl_df_met.iterrows():
if clst_i in list_clust:
plot_title = f"cluster {cl_met[clst_i]} (quality={row['quality_score']}, n={row['n']})"
color_c = cl_met[clst_i]
fig = px.line(df2.values,
y = list_clust,
labels={"variable": "Cluster"},
title=plot_title,
)
st.plotly_chart(fig)
# Create a figure to plot all clusters
all_clusters_fig = go.Figure()
clustered_data = df2.groupby(mod_choice.labels_, axis=1)
# Filter out clusters that are not in list_clust
clustered_data = {k: v for k, v in clustered_data if k in list_clust}
# Create dictionaries to hold the mean, max, and min values for each cluster
mean_data = {}
upper_quartile = {}
lower_quartile = {}
# Calculate the mean, max, and min for each cluster and add traces to the 'all_clusters_fig'
for cluster_id in list_clust:
plot_title = f"Cluster {cluster_id} - Mean, Max, and Min Lines"
mean_data[cluster_id] = clustered_data[cluster_id].mean(axis=1)
upper_quartile[cluster_id] = clustered_data[cluster_id].max(axis=1)
lower_quartile[cluster_id] = clustered_data[cluster_id].min(axis=1)
# Add mean line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=mean_data[cluster_id], mode='lines', name=f'Mean (Cluster {cluster_id})'))
# Add max line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=upper_quartile[cluster_id], mode='lines', name=f'Max (Cluster {cluster_id})', line=dict(color='lightgray')))
# Add min line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=lower_quartile[cluster_id], mode='lines', name=f'Min (Cluster {cluster_id})', fill='tonexty', line=dict(color='lightgray')))
all_clusters_fig.update_layout(
xaxis_title="Metrics",
yaxis_title="Values",
title=plot_title,
)
# Aggregate the mean, max, and min values across all clusters
mean_aggregated = np.mean([mean_data[cluster_id] for cluster_id in list_clust], axis=0)
max_aggregated = np.max([upper_quartile[cluster_id] for cluster_id in list_clust], axis=0)
min_aggregated = np.min([lower_quartile[cluster_id] for cluster_id in list_clust], axis=0)
# Create a 3-line plot with the original clusters and the aggregated lines
plot_title = f"All Clusters - Original and Aggregated Lines"
all_clusters_fig = go.Figure()
for cluster_id in list_clust:
# Add original cluster line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=mean_data[cluster_id], mode='lines', name=f'Cluster {cluster_id}'))
# Add aggregated mean line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=mean_aggregated, mode='lines', name='Aggregated Mean', line=dict(color='black')))
# Add aggregated max line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=max_aggregated, mode='lines', name='Aggregated Max', line=dict(color='lightgray')))
# Add aggregated min line
all_clusters_fig.add_trace(go.Scatter(x=df2.columns, y=min_aggregated, mode='lines', name='Aggregated Min', fill='tonexty', line=dict(color='lightgray')))
all_clusters_fig.update_layout(
xaxis_title="Metrics",
yaxis_title="Values",
title=plot_title,
)
# Plotting every clusters
if st.checkbox("Visualize all clusters"):
# Customize this part based on your preferences
all_clusters_fig.update_layout(
showlegend=True, # Show legend to distinguish clusters
title="All Clusters with Original and Aggregated Lines"
)
st.plotly_chart(all_clusters_fig)
# Getting cluster centers
if st.checkbox("Print cluster centers"):
cen_df_cl = pd.DataFrame(mod_choice.cluster_centers_.reshape(mod_choice.cluster_centers_.shape[0],
mod_choice.cluster_centers_.shape[
1])).transpose()
cen_df_cl.index = df2.index
for cluster in cl_df_met.index:
print('\n'.join(textwrap.wrap(
f"Cluster {cluster} (n={cl_count[cluster]}, score = {d_cl_qua[cluster]})",
width=175, replace_whitespace=False)))
print(f"CLuster distribution = {(cl_met[cluster])}")
col1, col2, col3, col4 = st.columns(4)
with col1:
col1.subheader("Cluster")
col1.write(cluster)
with col2:
col2.subheader("n=")
col2.write(cl_count)
with col3:
col3.subheader("score=")
col3.write(d_cl_qua)
with col4:
col4.subheader("Cluster distribution")
col4.write(cl_met)
fig = px.line(cen_df_cl,
title=f"Cluster {cluster} Centers",
labels={"variable": "Cluster"},
)
st.plotly_chart(fig)
###########################################
### Evaluate Clustering ###
###########################################
if st.sidebar.checkbox("Evaluate Cluster"):
st.subheader("Evaluate Clustering")
s_c = st.expander("Summary")
if mod_choice == 'hierarchical':
s_c.write(f"{mod_choice} clustering with {dis_choice} Affinity and with "
f"{link_choice} linkage method and {n_clusters} clusters were created."
f"The measured execution time was {time.perf_counter() - start_time} seconds.")
else:
s_c.write(f"{mod_choice} clustering with {dis_choice} distance."
f"{n_clusters} clusters were created. "
f"The measured execution time was {time.perf_counter() - start_time} seconds.")
###########################################
### CVI's ###
###########################################
st.write('Select Cluster Validity Index')
indec_si = st.expander("Silhouette score (SI)")
indec_si.write(silhouette_avrg)
indec_ch = st.expander("Calinski Harabasz Index (CH)")
calinski_harabasz_index = calinski_harabasz_score(X, mod_choice.labels_)
indec_ch.write(calinski_harabasz_index)
indec_db = st.expander("Davies Bouldin Index (DB)")
davies_bouldin_index = davies_bouldin_score(X, mod_choice.labels_)
indec_db.write(davies_bouldin_index)
# creating a data frame
cvi = pd.DataFrame([['SI',silhouette_avrg ], ['CH', calinski_harabasz_index], ['DB', davies_bouldin_index]],
columns=['CVI', 'Index Score'])
# writing data frame to a CSV file
cl_cui = cvi.to_csv()
#csv = pd.DataFrame(matrix).to_csv()
col1, col2, col3 = st.columns(3)
with col1:
pass
with col3:
pass
with col2:
center_button = st.download_button(
label="Download CVI's",
data=cl_cui,
file_name='cvis.csv',
mime='text/csv',
)
# squared distance to cluster center
## Getting the Distance matrix
n_df = (df2.values)
#print("Last Data frame ", df2, " is.")
(df2.values).shape
matrix = np.zeros(((df2.values).shape[0], (df2.values).shape[0]))
for i in range((df2.values).shape[0]):
for j in range((df2.values).shape[0]):
matrix[i, j] = np.sqrt(np.sum((n_df[i] - n_df[j]) ** 2))
f_c = st.expander("Cross distance matrix")
f_c.write(matrix)
csv = pd.DataFrame(matrix).to_csv()
"""ddf = pd.DataFrame(df, columns=['Month', 'Weekday', 'Hour']) ## I need this only for example comment
dd_cluster = pd.DataFrame(cl_df, columns=['cluster'])
df3 = [dd_cluster, ddf]
df_final = pd.concat(df3, axis=1)
df_final['cluster'] = df_final['cluster'].fillna(df_final['cluster'].median())
df_final['cluster'] = df_final['cluster'].astype(int)
file_con = st.expander("Data Set with Metric and Cluster")
file_con.write(df_final) # needs more evelopment"""
col1, col2, col3 = st.columns(3)
with col1:
pass
with col3:
pass
with col2:
center_button = st.download_button(
label="Download Distance matrix",
data=csv,
file_name='Distance_matrix.csv',
mime='text/csv',
)
File added
File added
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.