File size: 3,167 Bytes
7f50cd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | """Shared feature preparation, provenance, and the published RF recipe."""
import hashlib
import json
import multiprocessing
import os
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / 'vendor' / 'site-packages'))
sys.path.insert(0, os.environ['CORE_DIR'])
import numpy as np
from descriptors import describe
def worker_count(limit):
available = len(os.sched_getaffinity(0)) if hasattr(os, 'sched_getaffinity') else (os.cpu_count() or 1)
return max(1, min(limit, available))
def feature_version():
digest = hashlib.sha256()
for name in ('descriptors.py', 'elements.json'):
digest.update((HERE / name).read_bytes())
return digest.hexdigest()
def record_id(row):
# Identifiers only prevent adding the same practice training row twice.
# Neither this hash nor the opaque key is a model feature.
payload = {name: row[name] for name in ('key', 'basis', 'points', 'kinds')}
data = json.dumps(payload, sort_keys=True, separators=(',', ':'), allow_nan=False)
return hashlib.sha256(data.encode('utf-8')).hexdigest()
def featurize(rows, workers):
start = time.monotonic()
values = []
if not rows:
return np.empty((0, 273), dtype=np.float64)
with multiprocessing.get_context('spawn').Pool(worker_count(workers)) as pool:
for i, value in enumerate(pool.imap(describe, rows, chunksize=20), 1):
values.append(value)
if i % 500 == 0:
print(f'features {i}/{len(rows)}: {time.monotonic()-start:.3f}s', file=sys.stderr, flush=True)
features = np.asarray(values, dtype=np.float64)
failed = int(np.isnan(features).any(axis=1).sum())
print(f'features complete: {len(rows)} rows, {failed} with missing values, '
f'{time.monotonic()-start:.3f}s', file=sys.stderr, flush=True)
return features
def make_model(workers):
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
return Pipeline([
('imputer', SimpleImputer()),
('scaler', StandardScaler()),
('model', RandomForestRegressor(
n_estimators=100, max_features=1/3, bootstrap=False,
random_state=0, n_jobs=worker_count(workers))),
])
def load_pool():
path = HERE / 'prepared' / 'training_pool.npz'
if not path.is_file():
raise RuntimeError('Missing visible-training feature pool. Run out/train.sh before grading.')
with np.load(path, allow_pickle=False) as pool:
if str(pool['feature_version'].item()) != feature_version():
raise RuntimeError('Feature pool was made with different descriptor code or elemental tables.')
x, y, ids = pool['features'], pool['responses'], pool['record_ids']
if x.shape != (len(y), 273) or ids.shape != y.shape or len(y) == 0:
raise ValueError('Malformed training feature pool.')
if not np.isfinite(y).all() or np.isinf(x).any():
raise ValueError('Invalid values in training feature pool.')
return x, y, ids
|