2020-12-10 19:04:33 +01:00
|
|
|
from sklearn.linear_model import LogisticRegression
|
2021-01-06 14:58:29 +01:00
|
|
|
from sklearn.model_selection import GridSearchCV
|
2021-01-20 17:03:12 +01:00
|
|
|
from sklearn.svm import LinearSVC, LinearSVR
|
2020-12-10 19:04:33 +01:00
|
|
|
import quapy as qp
|
|
|
|
import quapy.functional as F
|
2020-12-14 18:36:19 +01:00
|
|
|
import sys
|
2020-12-22 17:43:23 +01:00
|
|
|
import numpy as np
|
2021-01-20 17:03:12 +01:00
|
|
|
|
|
|
|
from NewMethods.methods import AveragePoolQuantification
|
2021-01-06 14:58:29 +01:00
|
|
|
from classification.methods import PCALR
|
2021-01-28 18:22:43 +01:00
|
|
|
from data import Dataset
|
2021-01-27 09:54:41 +01:00
|
|
|
from method.meta import EPACC
|
2020-12-29 20:33:59 +01:00
|
|
|
from quapy.model_selection import GridSearchQ
|
2021-01-28 18:22:43 +01:00
|
|
|
from tqdm import tqdm
|
|
|
|
import pandas as pd
|
|
|
|
|
|
|
|
sample_size=100
|
|
|
|
qp.environ['SAMPLE_SIZE'] = sample_size
|
|
|
|
|
|
|
|
np.random.seed(0)
|
|
|
|
|
|
|
|
nfolds=5
|
|
|
|
nrepeats=1
|
|
|
|
|
|
|
|
df = pd.DataFrame(columns=['dataset', 'method', 'mse'])
|
2021-02-09 11:48:16 +01:00
|
|
|
for datasetname in qp.datasets.UCI_DATASETS:
|
2021-01-28 18:22:43 +01:00
|
|
|
collection = qp.datasets.fetch_UCILabelledCollection(datasetname, verbose=False)
|
|
|
|
scores = []
|
|
|
|
pbar = tqdm(Dataset.kFCV(collection, nfolds=nfolds, nrepeats=nrepeats), total=nfolds*nrepeats)
|
|
|
|
for data in pbar:
|
|
|
|
pbar.set_description(f'{data.name}')
|
|
|
|
# learner = GridSearchCV(LogisticRegression(class_weight='balanced'), param_grid={'C': np.logspace(-3,3,7)}, n_jobs=-1)
|
|
|
|
learner = LogisticRegression(class_weight='balanced')
|
|
|
|
# model = qp.method.aggregative.CC(learner)
|
|
|
|
model = qp.method.meta.EHDy(learner, size=30, red_size=15, verbose=False)
|
|
|
|
model.fit(data.training)
|
|
|
|
err = qp.evaluation.artificial_sampling_eval(model, data.test, sample_size, n_prevpoints=101, n_jobs=-1,
|
|
|
|
error_metric='mse', verbose=False)
|
|
|
|
scores.append(err)
|
|
|
|
|
|
|
|
score = np.mean(scores)
|
|
|
|
df = df.append({
|
|
|
|
'dataset': datasetname,
|
|
|
|
'method': model.__class__.__name__,
|
|
|
|
'mse': score
|
|
|
|
}, ignore_index=True)
|
|
|
|
print(df)
|
2020-12-10 19:04:33 +01:00
|
|
|
|
2021-01-27 22:49:54 +01:00
|
|
|
sys.exit(0)
|
2021-01-06 14:58:29 +01:00
|
|
|
|
|
|
|
|
2021-01-28 18:22:43 +01:00
|
|
|
|
2021-01-06 14:58:29 +01:00
|
|
|
#param_grid = {'C': np.logspace(-3,3,7), 'class_weight': ['balanced', None]}
|
|
|
|
param_grid = {'C': np.logspace(0,3,4), 'class_weight': ['balanced']}
|
2021-01-19 18:26:40 +01:00
|
|
|
max_evaluations = 500
|
2020-12-14 18:36:19 +01:00
|
|
|
|
2020-12-29 20:33:59 +01:00
|
|
|
sample_size = qp.environ['SAMPLE_SIZE']
|
2021-01-15 17:42:19 +01:00
|
|
|
binary = False
|
2020-12-11 19:28:17 +01:00
|
|
|
svmperf_home = './svm_perf_quantification'
|
2020-12-10 19:04:33 +01:00
|
|
|
|
|
|
|
if binary:
|
2021-01-22 18:01:51 +01:00
|
|
|
#dataset = qp.datasets.fetch_reviews('kindle', tfidf=True, min_df=5)
|
|
|
|
dataset = qp.datasets.fetch_UCIDataset('german', verbose=True)
|
2021-01-06 14:58:29 +01:00
|
|
|
#qp.data.preprocessing.index(dataset, inplace=True)
|
2020-12-10 19:04:33 +01:00
|
|
|
|
|
|
|
else:
|
2021-01-22 18:01:51 +01:00
|
|
|
dataset = qp.datasets.fetch_twitter('gasp', for_model_selection=True, min_df=5, pickle=True)
|
2021-01-20 17:03:12 +01:00
|
|
|
#dataset.training = dataset.training.sampling(sample_size, 0.2, 0.5, 0.3)
|
2020-12-11 19:28:17 +01:00
|
|
|
|
2020-12-29 20:33:59 +01:00
|
|
|
print(f'dataset loaded: #training={len(dataset.training)} #test={len(dataset.test)}')
|
|
|
|
|
2020-12-10 19:04:33 +01:00
|
|
|
|
|
|
|
# training a quantifier
|
2020-12-29 20:33:59 +01:00
|
|
|
# learner = LogisticRegression(max_iter=1000)
|
2021-01-06 14:58:29 +01:00
|
|
|
#model = qp.method.aggregative.ClassifyAndCount(learner)
|
2020-12-29 20:33:59 +01:00
|
|
|
# model = qp.method.aggregative.AdjustedClassifyAndCount(learner)
|
2020-12-10 19:04:33 +01:00
|
|
|
# model = qp.method.aggregative.ProbabilisticClassifyAndCount(learner)
|
|
|
|
# model = qp.method.aggregative.ProbabilisticAdjustedClassifyAndCount(learner)
|
2021-01-06 14:58:29 +01:00
|
|
|
# model = qp.method.aggregative.HellingerDistanceY(learner)
|
2020-12-10 19:04:33 +01:00
|
|
|
# model = qp.method.aggregative.ExpectationMaximizationQuantifier(learner)
|
2020-12-11 19:28:17 +01:00
|
|
|
# model = qp.method.aggregative.ExplicitLossMinimisationBinary(svmperf_home, loss='q', C=100)
|
2020-12-22 17:43:23 +01:00
|
|
|
# model = qp.method.aggregative.SVMQ(svmperf_home, C=1)
|
2020-12-11 19:28:17 +01:00
|
|
|
|
2021-01-06 14:58:29 +01:00
|
|
|
#learner = PCALR()
|
|
|
|
#learner = NeuralClassifierTrainer(CNNnet(dataset.vocabulary_size, dataset.n_classes))
|
|
|
|
#print(learner.get_params())
|
|
|
|
#model = qp.method.meta.QuaNet(learner, sample_size, device='cpu')
|
|
|
|
|
|
|
|
#learner = GridSearchCV(LogisticRegression(max_iter=1000), param_grid=param_grid, n_jobs=-1, verbose=1)
|
2021-01-20 17:03:12 +01:00
|
|
|
#learner = LogisticRegression(max_iter=1000)
|
2021-01-19 18:26:40 +01:00
|
|
|
# model = qp.method.aggregative.ClassifyAndCount(learner)
|
|
|
|
|
2021-01-27 09:54:41 +01:00
|
|
|
param_mod_sel = {
|
|
|
|
'sample_size': 100,
|
|
|
|
'n_prevpoints': 21,
|
|
|
|
'n_repetitions': 5,
|
|
|
|
'verbose': False
|
|
|
|
}
|
|
|
|
common = {
|
|
|
|
'max_sample_size': 50,
|
|
|
|
'n_jobs': -1,
|
|
|
|
'param_grid': {'C': np.logspace(0,2,2), 'class_weight': ['balanced']},
|
|
|
|
'param_mod_sel': param_mod_sel,
|
|
|
|
'val_split': 0.4,
|
|
|
|
'min_pos': 10,
|
|
|
|
'size':6,
|
|
|
|
'red_size':3
|
|
|
|
}
|
|
|
|
|
|
|
|
# hyperparameters will be evaluated within each quantifier of the ensemble, and so the typical model selection
|
|
|
|
# will be skipped (by setting hyperparameters to None)
|
|
|
|
model = EPACC(LogisticRegression(max_iter=100), optim='mrae', policy='mrae', **common)
|
|
|
|
|
|
|
|
"""
|
2021-01-22 18:01:51 +01:00
|
|
|
Problemas:
|
|
|
|
- La interfaz es muy fea, hay que conocer practicamente todos los detalles así que no ahorra nada con respecto a crear
|
|
|
|
un objeto con otros anidados dentro
|
|
|
|
- El fit genera las prevalences random, y esto hace que despues de la model selection, un nuevo fit tire todo el trabajo
|
|
|
|
hecho.
|
|
|
|
- El fit de un GridSearcQ tiene dentro un best_estimator, pero después de la model selection, hacer fit otra vez sobre
|
|
|
|
este objeto no se limita a re-entrenar el modelo con los mejores parámetros, sino que inicia una nueva búsqueda
|
|
|
|
en modo grid search.
|
|
|
|
- Posible solución (no vale): sería hacer directamente model selection con el benchmark final, aunque esto haría que los hyper-
|
|
|
|
parámetros se buscasen en un conjunto diferente del resto de models....
|
|
|
|
- Posible solución:
|
|
|
|
- Elegir las prevalences en init
|
|
|
|
-
|
|
|
|
- Problema: el parámetro val_split es muy ambiguo en todo el framework. Por ejemplo, en EPACC podría ser un float que,
|
|
|
|
en el caso de un GridSearchQ podría referir al split de validación para los hyperparámetros o al split que usa PACC
|
|
|
|
para encontrar los parámetros...
|
|
|
|
"""
|
|
|
|
|
2021-01-22 09:58:12 +01:00
|
|
|
# regressor = LinearSVR(max_iter=10000)
|
|
|
|
# param_grid = {'C': np.logspace(-1,3,5)}
|
|
|
|
# model = AveragePoolQuantification(regressor, sample_size, trials=5000, n_components=500, zscore=False)
|
2021-01-19 18:26:40 +01:00
|
|
|
|
2021-01-22 09:58:12 +01:00
|
|
|
# model = qp.method.meta.EHDy(learner, param_grid=param_grid, optim='mae',
|
2021-01-06 14:58:29 +01:00
|
|
|
# sample_size=sample_size, eval_budget=max_evaluations//10, n_jobs=-1)
|
|
|
|
#model = qp.method.aggregative.ClassifyAndCount(learner)
|
2020-12-29 20:33:59 +01:00
|
|
|
|
2021-01-22 09:58:12 +01:00
|
|
|
# model = qp.method.meta.QuaNet(PCALR(n_components=100, max_iter=1000),
|
|
|
|
# sample_size=100,
|
|
|
|
# patience=10,
|
|
|
|
# tr_iter_per_poch=500, va_iter_per_poch=100, #lstm_nlayers=2, lstm_hidden_size=64,
|
|
|
|
# ff_layers=[500, 250, 50],
|
|
|
|
# checkpointdir='./checkpoint', device='cuda')
|
2021-01-06 14:58:29 +01:00
|
|
|
|
2021-01-15 17:42:19 +01:00
|
|
|
if qp.isbinary(model) and not qp.isbinary(dataset):
|
|
|
|
model = qp.method.aggregative.OneVsAll(model)
|
2020-12-09 12:46:50 +01:00
|
|
|
|
2020-12-10 19:04:33 +01:00
|
|
|
|
2020-12-22 17:43:23 +01:00
|
|
|
# Model fit and Evaluation on the test data
|
|
|
|
# ----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
print(f'fitting model {model.__class__.__name__}')
|
2020-12-29 20:33:59 +01:00
|
|
|
#train, val = dataset.training.split_stratified(0.6)
|
|
|
|
#model.fit(train, val_split=val)
|
2021-01-27 09:54:41 +01:00
|
|
|
qp.SAMPLE=1
|
|
|
|
qp.environ['SAMPLE_SIZE']=2
|
2021-01-20 17:03:12 +01:00
|
|
|
model.fit(dataset.training)
|
2021-01-19 18:26:40 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
2021-01-06 14:58:29 +01:00
|
|
|
|
2020-12-11 19:28:17 +01:00
|
|
|
|
2020-12-10 19:04:33 +01:00
|
|
|
# estimating class prevalences
|
2021-01-22 09:58:12 +01:00
|
|
|
# print('quantifying')
|
|
|
|
# prevalences_estim = model.quantify(dataset.test.instances)
|
|
|
|
# prevalences_true = dataset.test.prevalence()
|
|
|
|
#
|
2020-12-10 19:04:33 +01:00
|
|
|
# evaluation (one single prediction)
|
2021-01-22 09:58:12 +01:00
|
|
|
# error = qp.error.mae(prevalences_true, prevalences_estim)
|
|
|
|
#
|
|
|
|
# print(f'Evaluation in test (1 eval)')
|
|
|
|
# print(f'true prevalence {F.strprev(prevalences_true)}')
|
|
|
|
# print(f'estim prevalence {F.strprev(prevalences_estim)}')
|
|
|
|
# print(f'mae={error:.3f}')
|
2020-12-10 19:04:33 +01:00
|
|
|
|
|
|
|
|
2020-12-22 17:43:23 +01:00
|
|
|
# Model fit and Evaluation according to the artificial sampling protocol
|
|
|
|
# ----------------------------------------------------------------------------
|
|
|
|
|
2020-12-11 19:28:17 +01:00
|
|
|
n_prevpoints = F.get_nprevpoints_approximation(combinations_budget=max_evaluations, n_classes=dataset.n_classes)
|
|
|
|
n_evaluations = F.num_prevalence_combinations(n_prevpoints, dataset.n_classes)
|
2020-12-14 18:36:19 +01:00
|
|
|
print(f'the prevalence interval [0,1] will be split in {n_prevpoints} prevalence points for each class, so that\n'
|
|
|
|
f'the requested maximum number of sample evaluations ({max_evaluations}) is not exceeded.\n'
|
2020-12-11 19:28:17 +01:00
|
|
|
f'For the {dataset.n_classes} classes this dataset has, this will yield a total of {n_evaluations} evaluations.')
|
|
|
|
|
2020-12-29 20:33:59 +01:00
|
|
|
true_prev, estim_prev = qp.evaluation.artificial_sampling_prediction(model, dataset.test, sample_size, n_prevpoints)
|
2020-12-11 19:28:17 +01:00
|
|
|
|
2021-01-06 14:58:29 +01:00
|
|
|
#qp.error.SAMPLE_SIZE = sample_size
|
2020-12-10 19:04:33 +01:00
|
|
|
print(f'Evaluation according to the artificial sampling protocol ({len(true_prev)} evals)')
|
|
|
|
for error in qp.error.QUANTIFICATION_ERROR:
|
|
|
|
score = error(true_prev, estim_prev)
|
|
|
|
print(f'{error.__name__}={score:.5f}')
|
2020-12-10 19:08:22 +01:00
|
|
|
|
2021-01-22 09:58:12 +01:00
|
|
|
sys.exit(0)
|
2020-12-22 17:43:23 +01:00
|
|
|
# Model selection and Evaluation according to the artificial sampling protocol
|
|
|
|
# ----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
model_selection = GridSearchQ(model,
|
|
|
|
param_grid=param_grid,
|
2020-12-29 20:33:59 +01:00
|
|
|
sample_size=sample_size,
|
2020-12-22 17:43:23 +01:00
|
|
|
eval_budget=max_evaluations//10,
|
|
|
|
error='mae',
|
|
|
|
refit=True,
|
2021-01-15 17:42:19 +01:00
|
|
|
verbose=True,
|
2021-01-20 17:03:12 +01:00
|
|
|
timeout=60*60)
|
2020-12-22 17:43:23 +01:00
|
|
|
|
2021-01-19 18:26:40 +01:00
|
|
|
model = model_selection.fit(dataset.training, val_split=0.3)
|
2021-01-06 14:58:29 +01:00
|
|
|
#model = model_selection.fit(train, validation=val)
|
2020-12-22 17:43:23 +01:00
|
|
|
print(f'Model selection: best_params = {model_selection.best_params_}')
|
|
|
|
print(f'param scores:')
|
|
|
|
for params, score in model_selection.param_scores_.items():
|
|
|
|
print(f'\t{params}: {score:.5f}')
|
|
|
|
|
2020-12-29 20:33:59 +01:00
|
|
|
true_prev, estim_prev = qp.evaluation.artificial_sampling_prediction(model, dataset.test, sample_size, n_prevpoints)
|
2020-12-22 17:43:23 +01:00
|
|
|
|
|
|
|
print(f'After model selection: Evaluation according to the artificial sampling protocol ({len(true_prev)} evals)')
|
|
|
|
for error in qp.error.QUANTIFICATION_ERROR:
|
|
|
|
score = error(true_prev, estim_prev)
|
|
|
|
print(f'{error.__name__}={score:.5f}')
|