Commit bb29ca71 authored by Muniza's avatar Muniza
Browse files

Initial commit

parents
[flake8]
max-line-length = 88
\ No newline at end of file
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-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
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# 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/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.vscode/
\ No newline at end of file
__version__ = '0.1.0'
import argparse
import json
import logging
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Tuple
import pandas as pd
from sklearn.metrics import confusion_matrix
from xgboost import XGBClassifier
@dataclass(frozen=True)
class Performance:
true_positive: int
true_negative: int
false_positive: int
false_negative: int
LABEL = "damaging"
FEATURES = [
"delta_num_categories",
"delta_num_headings",
"delta_num_media",
"delta_num_refs",
"delta_num_wikilinks",
"delta_page_length",
]
def split_by_language(
data_df: pd.DataFrame, wiki_db: str
) -> Tuple[pd.DataFrame, pd.DataFrame]:
language_df = data_df[data_df["wiki_db"] == wiki_db]
other_languages_df = data_df[data_df["wiki_db"] != wiki_db]
return language_df, other_languages_df
def train(X: pd.DataFrame, y: pd.Series) -> XGBClassifier:
logging.info(f"Training gradient boosted classifier: {len(X)} examples")
model = XGBClassifier()
model.fit(X, y, verbose=True)
return model
def calculate_performance(
model: XGBClassifier, X: pd.DataFrame, y: pd.Series
) -> Performance:
logging.info(f"Calculating model performance metrics: {len(X)} examples")
y_pred = model.predict(X)
tn, fp, fn, tp = confusion_matrix(y, y_pred).ravel()
logging.info(f"tn: {tn}, fp: {fp}, fn: {fn}, tp: {tp}")
return Performance(
true_positive=int(tp),
true_negative=int(tn),
false_positive=int(fp),
false_negative=int(fn),
)
def main() -> None:
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument(
"--data",
type=Path,
required=True,
help="Path to training data",
)
parser.add_argument(
"--models",
type=Path,
required=True,
help="Directory to write the serialized models",
)
parser.add_argument(
"--performance",
type=Path,
required=True,
help="Directory to write the performance metrics for models",
)
args = parser.parse_args()
data_path = args.data
models_dir = args.models
performance_dir = args.performance
data_df = pd.read_csv(data_path, sep="\t", compression="gzip")
data_df = data_df[~data_df[LABEL].isnull()]
data_df[LABEL] = data_df[LABEL].astype(bool)
logging.info(f"Loaded {len(data_df)} training examples")
for wiki_db in data_df["wiki_db"].unique():
logging.info(f"Current language: {wiki_db}")
language_df, other_languages_df = split_by_language(data_df, wiki_db)
model = train(other_languages_df[FEATURES], other_languages_df[LABEL])
model_performance = calculate_performance(
model, language_df[FEATURES], language_df[LABEL]
)
model_path = models_dir / f"{wiki_db}.json"
logging.info(f"Writing model to {model_path}")
model.save_model(model_path)
performance_path = performance_dir / f"{wiki_db}.json"
logging.info(f"Writing model performance metrics to {performance_path}")
with open(performance_path, "w") as f:
json.dump(asdict(model_performance), f)
if __name__ == "__main__":
main()
This diff is collapsed.
[tool.poetry]
name = "language-models"
version = "0.1.0"
description = ""
authors = ["Muniza <maslam-ctr@wikimedia.org>"]
[tool.poetry.dependencies]
python = "^3.7.2"
xgboost = "^1.6.1"
pandas = "1.3"
scikit-learn = "1.0"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
flake8 = "^5.0.1"
black = "^22.6.0"
isort = "^5.10.1"
mypy = "^0.971"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment