9 Commits

Author SHA1 Message Date
bastien ollier
c8cf0fe045 add stats 2024-06-25 08:33:32 +02:00
4d82767c68 Add SkLearn to requirements.txt 2024-06-21 16:59:51 +02:00
Bastien OLLIER
9cb0d90eb1 Add CI/CD (#9)
Co-authored-by: clfreville2 <clement.freville2@etu.uca.fr>
Co-authored-by: bastien ollier <bastien.ollier@etu.uca.fr>
Reviewed-on: https://codefirst.iut.uca.fr/git/clement.freville2/miner/pulls/9
Reviewed-by: Clément FRÉVILLE <clement.freville2@etu.uca.fr>
Co-authored-by: Bastien OLLIER <bastien.ollier@noreply.codefirst.iut.uca.fr>
Co-committed-by: Bastien OLLIER <bastien.ollier@noreply.codefirst.iut.uca.fr>
2024-06-21 16:53:00 +02:00
Bastien OLLIER
3eac3f6b8d Merge pull request 'Support multiple column delimiters' (#10) from csv-delimiters into main
Reviewed-on: https://codefirst.iut.uca.fr/git/clement.freville2/miner/pulls/10
2024-06-21 16:49:01 +02:00
c87308cc21 Support multiple column delimiters 2024-06-21 16:46:35 +02:00
d4aeb87f75 Limit the number of neighbors based on the dataframe 2024-06-21 16:09:30 +02:00
Hugo PRADIER
3c5f6849f8 Merge pull request 'Support kNN as an imputation method' (#8) from knn into main
Reviewed-on: https://codefirst.iut.uca.fr/git/clement.freville2/miner/pulls/8
2024-06-21 15:51:46 +02:00
cd0c85ea44 Support kNN as an imputation method 2024-06-21 15:45:33 +02:00
Hugo PRADIER
96d390c749 Merge pull request 'Ajout de la prédiction avec deux algos (un de prédiction et un de classification)' (#7) from prediction into main
Reviewed-on: https://codefirst.iut.uca.fr/git/clement.freville2/miner/pulls/7
Reviewed-by: Clément FRÉVILLE <clement.freville2@etu.uca.fr>
2024-06-21 14:56:28 +02:00
9 changed files with 186 additions and 19 deletions

44
.drone.yml Normal file
View File

@@ -0,0 +1,44 @@
kind: pipeline
name: default
type: docker
trigger:
event:
- push
steps:
- name: lint
image: python:3.12
commands:
- pip install --root-user-action=ignore -r requirements.txt
- ruff check .
- name: docker-image
image: plugins/docker
settings:
dockerfile: Dockerfile
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/bastien.ollier/miner
username:
from_secret: REGISTRY_USER
password:
from_secret: REGISTRY_PASSWORD
cache_from:
- hub.codefirst.iut.uca.fr/bastien.ollier/miner:latest
depends_on: [ lint ]
- name: deploy-miner
image: hub.codefirst.iut.uca.fr/clement.freville2/codefirst-dockerproxy-clientdrone:latest
settings:
image: hub.codefirst.iut.uca.fr/bastien.ollier/miner:latest
container: miner
command: create
overwrite: true
admins: bastienollier,clementfreville2,hugopradier2
environment:
DRONE_REPO_OWNER: bastien.ollier
depends_on: [ docker-image ]
when:
branch:
- main
- ci/*

9
Dockerfile Normal file
View File

@@ -0,0 +1,9 @@
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip3 install -r requirements.txt
EXPOSE 80
ENTRYPOINT ["streamlit", "run", "frontend/exploration.py", "--server.port=80", "--server.address=0.0.0.0", "--server.baseUrlPath=/containers/bastienollier-miner"]

63
frontend/clusters.py Normal file
View File

@@ -0,0 +1,63 @@
from sklearn.cluster import DBSCAN, KMeans
import numpy as np
class DBSCAN_cluster():
def __init__(self, eps, min_samples,data):
self.eps = eps
self.min_samples = min_samples
self.data = data
self.labels = np.array([])
def run(self):
dbscan = DBSCAN(eps=self.eps, min_samples=self.min_samples)
self.labels = dbscan.fit_predict(self.data)
return self.labels
def get_stats(self):
unique_labels = np.unique(self.labels)
stats = []
for label in unique_labels:
if label == -1:
continue
cluster_points = self.data[self.labels == label]
num_points = len(cluster_points)
density = num_points / (np.max(cluster_points, axis=0) - np.min(cluster_points, axis=0)).prod()
stats.append({
"cluster": label,
"num_points": num_points,
"density": density
})
return stats
class KMeans_cluster():
def __init__(self, n_clusters, n_init, max_iter, data):
self.n_clusters = n_clusters
self.n_init = n_init
self.max_iter = max_iter
self.data = data
self.labels = np.array([])
self.centers = []
def run(self):
kmeans = KMeans(n_clusters=self.n_clusters, init="random", n_init=self.n_init, max_iter=self.max_iter, random_state=111)
self.labels = kmeans.fit_predict(self.data)
self.centers = kmeans.cluster_centers_
return self.labels
def get_stats(self):
unique_labels = np.unique(self.labels)
stats = []
for label in unique_labels:
cluster_points = self.data[self.labels == label]
num_points = len(cluster_points)
center = self.centers[label]
stats.append({
'cluster': label,
'num_points': num_points,
'center': center
})
return stats

View File

@@ -1,5 +1,6 @@
import pandas as pd
import streamlit as st
import codecs
st.set_page_config(
page_title="Project Miner",
@@ -9,10 +10,13 @@ st.set_page_config(
st.title("Home")
### Exploration
uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
uploaded_file = st.file_uploader("Upload your CSV file", type=["csv", "tsv"])
separator = st.selectbox("Separator", [",", ";", "\\t"])
separator = codecs.getdecoder("unicode_escape")(separator)[0]
has_header = st.checkbox("Has header", value=True)
if uploaded_file is not None:
st.session_state.data = pd.read_csv(uploaded_file)
st.session_state.data = pd.read_csv(uploaded_file, sep=separator, header=0 if has_header else 1)
st.session_state.original_data = st.session_state.data
st.success("File loaded successfully!")

View File

@@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
from pandas import DataFrame, Series
from pandas.api.types import is_numeric_dtype
from sklearn.neighbors import KNeighborsClassifier
from typing import Any, Union
class DataFrameFunction(ABC):
@@ -18,11 +19,14 @@ class MVStrategy(DataFrameFunction):
"""A way to handle missing values in a dataframe."""
@staticmethod
def list_available(df: DataFrame, series: Series) -> list['MVStrategy']:
def list_available(df: DataFrame, label: str, series: Series) -> list['MVStrategy']:
"""Get all the strategies that can be used."""
choices = [DropStrategy(), ModeStrategy()]
if is_numeric_dtype(series):
choices.extend((MeanStrategy(), MedianStrategy(), LinearRegressionStrategy()))
other_columns = df.select_dtypes(include="number").drop(label, axis=1).columns.to_list()
if len(other_columns):
choices.append(KNNStrategy(other_columns))
return choices
@@ -97,6 +101,43 @@ class LinearRegressionStrategy(MVStrategy):
return "Use linear regression"
class KNNStrategy(MVStrategy):
def __init__(self, training_features: list[str]):
self.available_features = training_features
self.training_features = training_features
self.n_neighbors = 3
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
# Remove any training column that have any missing values
usable_data = df.dropna(subset=self.training_features)
# Select columns to impute from
train_data = usable_data.dropna(subset=label)
# Create train dataframe
x_train = train_data.drop(label, axis=1)
y_train = train_data[label]
reg = KNeighborsClassifier(self.n_neighbors).fit(x_train, y_train)
# Create test dataframe
test_data = usable_data[usable_data[label].isnull()]
if test_data.empty:
return df
x_test = test_data.drop(label, axis=1)
predicted = reg.predict(x_test)
# Fill with predicated values and patch the original data
usable_data[label].fillna(Series(predicted), inplace=True)
df.fillna(usable_data, inplace=True)
return df
def count_max(self, df: DataFrame, label: str) -> int:
usable_data = df.dropna(subset=self.training_features)
return usable_data[label].count()
def __str__(self) -> str:
return "kNN"
class KeepStrategy(ScalingStrategy):
#@typing.override
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:

View File

@@ -1,10 +1,9 @@
import streamlit as st
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from clusters import DBSCAN_cluster
st.header("Clustering: dbscan")
if "data" in st.session_state:
data = st.session_state.data
@@ -17,8 +16,9 @@ if "data" in st.session_state:
if len(data_name) >= 2 and len(data_name) <=3:
x = data[data_name].to_numpy()
dbscan = DBSCAN(eps=eps, min_samples=min_samples)
y_dbscan = dbscan.fit_predict(x)
dbscan = DBSCAN_cluster(eps,min_samples,x)
y_dbscan = dbscan.run()
st.table(dbscan.get_stats())
fig = plt.figure()
if len(data_name) == 2:
@@ -28,8 +28,5 @@ if "data" in st.session_state:
ax = fig.add_subplot(projection='3d')
ax.scatter(x[:, 0], x[:, 1],x[:, 2], c=y_dbscan, s=50, cmap="viridis")
st.pyplot(fig)
else:
st.error("file not loaded")

View File

@@ -1,10 +1,9 @@
import streamlit as st
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from clusters import KMeans_cluster
st.header("Clustering: kmeans")
if "data" in st.session_state:
data = st.session_state.data
@@ -23,20 +22,21 @@ if "data" in st.session_state:
if len(data_name) >= 2 and len(data_name) <=3:
x = data[data_name].to_numpy()
kmeans = KMeans(n_clusters=n_clusters, init="random", n_init=n_init, max_iter=max_iter, random_state=111)
y_kmeans = kmeans.fit_predict(x)
kmeans = KMeans_cluster(n_clusters, n_init, max_iter, x)
y_kmeans = kmeans.run()
st.table(kmeans.get_stats())
centers = kmeans.centers
fig = plt.figure()
if len(data_name) == 2:
ax = fig.add_subplot(projection='rectilinear')
plt.scatter(x[:, 0], x[:, 1], c=y_kmeans, s=50, cmap="viridis")
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c="black", s=200, marker="X")
else:
ax = fig.add_subplot(projection='3d')
ax.scatter(x[:, 0], x[:, 1],x[:, 2], c=y_kmeans, s=50, cmap="viridis")
centers = kmeans.cluster_centers_
ax.scatter(centers[:, 0], centers[:, 1], centers[:, 2], c="black", s=200, marker="X")
st.pyplot(fig)

View File

@@ -1,5 +1,5 @@
import streamlit as st
from normstrategy import MVStrategy, ScalingStrategy
from normstrategy import MVStrategy, ScalingStrategy, KNNStrategy
if "data" in st.session_state:
data = st.session_state.original_data
@@ -8,13 +8,16 @@ if "data" in st.session_state:
for column, series in data.items():
col1, col2 = st.columns(2)
missing_count = series.isna().sum()
choices = MVStrategy.list_available(data, series)
choices = MVStrategy.list_available(data, column, series)
option = col1.selectbox(
f"Missing values of {column} ({missing_count})",
choices,
index=1,
key=f"mv-{column}",
)
if isinstance(option, KNNStrategy):
option.training_features = st.multiselect("Training columns", option.training_features, default=option.available_features, key=f"cols-{column}")
option.n_neighbors = st.number_input("Number of neighbors", min_value=1, max_value=option.count_max(data, column), value=option.n_neighbors, key=f"neighbors-{column}")
# Always re-get the series to avoid reusing an invalidated series pointer
data = option.apply(data, column, data[column])

6
requirements.txt Normal file
View File

@@ -0,0 +1,6 @@
matplotlib>=3.5.0
pandas>=1.5.0
seaborn>=0.12.0
scikit-learn>=0.23.0
streamlit>=1.35.0
ruff>=0.4.8