Skip to content

Commit

Permalink
Init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
phiyodr committed Dec 21, 2022
0 parents commit cb8d9fc
Show file tree
Hide file tree
Showing 9 changed files with 418 additions and 0 deletions.
166 changes: 166 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# Initially taken from Github's Python gitignore file

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# tests and logs
tests/fixtures/cached_*_text.txt
logs/
lightning_logs/
lang_code_data/

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# vscode
.vs
.vscode

# Pycharm
.idea

# TF code
tensorflow_code

# Models
proc_data

# examples
runs
/runs_old
/wandb
/examples/runs
/examples/**/*.args
/examples/rag/sweep

# data
/data
serialization_dir

# emacs
*.*~
debug.env

# vim
.*.swp

#ctags
tags

# pre-commit
.pre-commit*

# .lock
*.lock

# DS_Store (MacOS)
.DS_Store
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2022 Philipp J. Rösch

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Multilabel Oversampling

**Many algorithms for imbalanced data support binary and multiclass classification only.**
**This approach is made for mulit-label classification (aka multi-target classification).**



## :slot_machine: Algorithm

* Multilabel dataset (as `pandas.DataFrame`) with imbalanced data
* Calculate counts per class and then calculate the standard deviation (std) of the count values
* Do for `number_of_adds` times the following:
* Randomly draw a sample from your data and calculate new std
* If new std reduces, add sample to your dataset
* If not, draw another sample (to this up to `number_of_tries` times)
* A new df is returned.
* A result plot viszualize the target distribition before and after upsampling. Moreover the counts per index are shown.

## :arrow_right: Usage

```python
from multilabel_oversampling import multilabel_oversampling as mo

df = mo.create_fake_data(size=1, seed=3)
ml_oversampler = mo.MultilabelOversampler(number_of_adds=100, number_of_tries=100)
df_new = ml_oversampler.fit(df)
#> Iteration: 20%|██████ | 20/100 [00:00<00:00, 111.68it/s]
#> No improvement after 100 tries in iter 20.
```
![Plot from df_new = ml_oversampler.fit(df)](assets/plot.png)

```python
ml_oversampler.plot_results()
```

![Plot from ml_oversampler.plot_results()](assets/plot_results.png)

## :information_source: Install

* Install from GitHub

```bash
pip install git+https://github.com/phiyodr/multilabel-oversampling
```

:sunflower:
Binary file added assets/plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/plot_results.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions multilabel_oversampling/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .multilabel_oversampling import *
156 changes: 156 additions & 0 deletions multilabel_oversampling/multilabel_oversampling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
import copy
import seaborn as sns
from tqdm import tqdm
import matplotlib.pyplot as plt
import random
import os
import math


def seed_everything(seed=1):
""""
Seed everything.
"""
random.seed(seed)
np.random.seed(seed)

def create_fake_data(size=1, seed=1):
seed_everything(seed)
y1 = np.concatenate((np.ones(16*size), np.zeros(4*size))).astype(int)
y2 = np.concatenate((np.ones(12*size), np.zeros(8*size))).astype(int)
y3 = shuffle(np.concatenate((np.ones(4*size), np.zeros(16*size)))).astype(int)
y4 = shuffle(np.concatenate((np.ones(4*size), np.zeros(16*size)))).astype(int)
size = 20* size
x = [f"img_{x}.jpg" for x in range(size)]
df = pd.DataFrame({"y1": y1, "y2": y2, "y3": y3, "y4": y4, "x": x})
return df

class MultilabelOversampler:

def __init__(self, number_of_adds=1000, number_of_tries=100, tqdm_disable=False, details=False, plot=True):
"""
Args:
number_of_add: Maximum number of new rows add to df. Total number of iterations.
number_of_tries: Maximum number of draws from df within total number of iterations.
tqdm_disable: Enable progress bar for each iteration.
details: Enable detailed feedback for each try
plot: Plot all tries (iteration vs. std) after process is finished.
"""
if number_of_adds:
self.number_of_adds = number_of_adds
else:
self.number_of_adds = 1e6
if number_of_tries:
self.number_of_tries = number_of_tries
else:
self.number_of_tries = 1e6

self.tqdm_disable = tqdm_disable
self.details = details
self.plot = plot


def fit(self, df, target_list=["y1", "y2", "y3", "y4"]):
"""
Args:
df: Unbalanced DataFrame
target_list: List of target variables. All other variables are treated as explanatory variables.
"""
self.reset()
self.target_list = target_list
self.df = copy.deepcopy(df)
df_new = copy.deepcopy(df)
res_std = []
res_bad = []


for iter_ in tqdm(range(self.number_of_adds),desc="Iteration", disable=self.tqdm_disable):
current_std = df_new[self.target_list].sum().std()

# Take random row and add to df_new
not_working = []
for try_ in tqdm(range(self.number_of_tries), desc=f"Iter {iter_}", disable=True):
random_row = df.sample(n = 1)
df_interim = pd.concat((df_new, random_row))
new_std = df_interim[self.target_list].sum().std()
# If std improves add row, otherwise add to not_working list
if new_std < current_std:
df_new = df_interim
res_std.append(new_std)
if self.details:
print(f"Iter {iter_:3}: Worked after {try_:5} tries with row {random_row.index[0]:4}, Std: {current_std:.3f}, New: {new_std:.3f}, Shape: {df_new.shape}", flush=True)
break
else:
not_working.append((random_row.index[0], new_std))
if (try_+1) == self.number_of_tries:
print(f"No improvement after {self.number_of_tries} tries in iter {iter_}.")
break
res_bad.append(not_working)
#plt.plot(res_std)
#plt.show()
#df_new.sum().plot.bar()
self.df_new = df_new
self.res_std = res_std
self.res_bad = res_bad
if (len(res_std) > 0) and self.plot:
self.plot_all_tries(self.res_std, self.res_bad)
plt.show()
return df_new

def reset(self):
self.target_list = None
self.df = None
self.df_new = None
self.res_std = None
self.res_bad = None

@staticmethod
def plot_all_tries(res_std, res_bad):
y_max = max([x[1] for x in res_bad[0]]) * 1.1
plt.plot(res_std)
plt.scatter(range(len(res_std)), res_std)
plt.ylim(0, y_max)
for i, row_std in enumerate(res_bad):
for idx, (j, s) in enumerate(row_std):
#plt.text(i + idx*0.02, s, f"{j}", fontsize=8)
plt.scatter(i + idx*0.01, s)
plt.xlabel('Iters')#, fontsize=18)
plt.ylabel('Std')#, fontsize=16)

def plot_results(self):
plt.subplot(2,2,1)
self.plot_distr(self.df, "before")
plt.subplot(2,2,2)
self.plot_distr(self.df_new, "after")
plt.subplot(2,2,(3,4)) # MatplotlibDeprecationWarning
self.plot_index_counts(self.df_new)
plt.tight_layout()
plt.show()

def plot_distr(self, df, when):
df[self.target_list].sum().plot.bar()
plt.title(f"Label distribution \n{when} upsampling")
return plt

def plot_index_counts(self, df_new):
"""TODO make better xticks alignment"""
idxs = list(df_new.index)
lens = len(set(idxs))
plt.hist(idxs, bins=lens, width=.1)#, edgecolor='k')
xint = range(min(idxs), math.ceil(max(idxs))+1)
plt.xticks(xint)
plt.title("Draws per index\n in new df")
return plt

if __name__ == '__main__':
df = create_fake_data(size=1, seed=3)
print(df)
mlo = MultilabelOversampling(number_of_adds=100)
df_new = mlo.fit(df)
mlo.plot_results()
6 changes: 6 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
numpy
scikit-learn
pandas
seaborn
tqdm
matplotlib
Loading

0 comments on commit cb8d9fc

Please sign in to comment.