73 lines
2.6 KiB
Python
73 lines
2.6 KiB
Python
import argparse
|
|
import pandas as pd
|
|
import seaborn as sns
|
|
|
|
from glob import glob
|
|
from pathlib import Path
|
|
|
|
from sklearn.model_selection import cross_validate
|
|
from sklearn.linear_model import LogisticRegression
|
|
from sklearn.pipeline import make_pipeline
|
|
from sklearn.preprocessing import StandardScaler
|
|
|
|
# simple command line interface
|
|
|
|
parser = argparse.ArgumentParser(
|
|
description='''This script fits a regression model on external input data
|
|
from penguin beak measurements and uses the model to predict Species
|
|
membership of own measurements. ''')
|
|
parser.add_argument('-i', '--input',
|
|
type=str,
|
|
default='inputs/',
|
|
help='''
|
|
Path to an input dataset with penguin data. The dataset
|
|
should contain csv tables with the columns "Culmen Length
|
|
(mm)" and "Culmen Depth (mm)".''')
|
|
parser.add_argument('-m', '--measurements',
|
|
default='data/local-samples.csv',
|
|
help='''
|
|
Path to a csv file with own beak measurements. Should
|
|
contain columns "Culmen Length (mm)" and "Culmen Depth (mm)
|
|
".''')
|
|
parser.add_argument('-o', '--output',
|
|
default='predictions.csv',
|
|
help='''
|
|
Path where results shall be saved as a csv file.''')
|
|
args = parser.parse_args()
|
|
# extract commandline arguments:
|
|
measurements = Path(args.measurements)
|
|
inputs = Path(args.input)
|
|
|
|
# find all tables
|
|
files = sorted(inputs.glob('*/*table*.csv'))
|
|
|
|
# combine the data into a single DataFrame
|
|
dfs = []
|
|
for file in files:
|
|
df = pd.read_csv(file)
|
|
dfs.append(df)
|
|
|
|
combined_data = pd.concat(dfs, ignore_index=True)
|
|
|
|
# read local samples
|
|
local_samples = pd.read_csv(measurements,
|
|
usecols=['Culmen Length (mm)', 'Culmen Depth (mm)'])
|
|
|
|
# define features and targets, build a smaller dataset
|
|
penguins = combined_data[["Culmen Length (mm)", "Culmen Depth (mm)", "Species"]]
|
|
penguins = penguins.dropna()
|
|
data, target = penguins.drop(columns="Species"), penguins["Species"]
|
|
|
|
|
|
# build a pipeline with a Logistic Regression
|
|
model = make_pipeline(StandardScaler(), LogisticRegression())
|
|
# evaluate the model using cross-validation
|
|
cv_result = cross_validate(model, data, target, cv=3)
|
|
print(f'average model accuracy is {cv_result["test_score"].mean():.3f}')
|
|
|
|
# fit the model on data; predict Species of own data points
|
|
model.fit(data, target)
|
|
res = model.predict(local_samples)
|
|
local_samples['prediction'] = res
|
|
# save the prediction
|
|
local_samples.to_csv(args.output)
|