A programming framework for agentic AI
Fix #11; add tests for training log and python logger (#12)
Eric Zhu4ce908f42ed2
diff --git a/flaml/__init__.py b/flaml/__init__.pyindex 2de9646dc..309cac7c2 100644--- a/flaml/__init__.py+++ b/flaml/__init__.py@@ -1,70 +1,17 @@from flaml.automl import AutoML+import logging+from flaml.model import BaseEstimatorfrom flaml.data import get_output_from_log-from flaml.version import __version__-import logging-from os.path import join, exists-import datetime as dt-from os import listdir, remove, mkdir-import pathlib-import json--root = pathlib.Path(__file__).parent.parent.absolute()-jsonfilepath = join(root, "settings.json")--with open(jsonfilepath) as f:- settings = json.load(f)--logging_level = settings["logging_level"]--if logging_level == "info":- logging_level = logging.INFO-elif logging_level == "debug":- logging_level = logging.DEBUG-elif logging_level == "error":- logging_level = logging.ERROR-elif logging_level == "warning":- logging_level = logging.WARNING-elif logging_level == "critical":- logging_level = logging.CRITICAL-else:- logging_level = logging.NOTSET--keep_max_logfiles = settings["keep_max_logfiles"]--log_dir = join(root, "logs")--if not exists(log_dir):- mkdir(log_dir)--del_logs = sorted([int(x.split("_")[0]) for x in listdir(log_dir) if ".log" in- x], reverse=True)[keep_max_logfiles:]--for l in del_logs:- try:- remove(join(log_dir, str(l) + "_flaml.log"))- except Exception as e:- continue--b = dt.datetime.now()-a = dt.datetime(2020, 4, 1, 0, 0, 0)-secs = int((b-a).total_seconds())-name = str(secs)-+# Set the root logger.logger = logging.getLogger(__name__)-logger.setLevel(logging_level)-fh = logging.FileHandler(join(log_dir, name + "_" + __name__ + ".log"))-fh.setLevel(logging_level)-ch = logging.StreamHandler()-ch.setLevel(logging_level)-# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')-formatter = logging.Formatter(++# Add the console handler.+_ch = logging.StreamHandler()+logger_formatter = logging.Formatter('[%(name)s: %(asctime)s] {%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')-ch.setFormatter(formatter)-fh.setFormatter(formatter)-logger.addHandler(ch)-logger.addHandler(fh)-logger.propagate = True+_ch.setFormatter(logger_formatter)+logger.addHandler(_ch)diff --git a/flaml/automl.py b/flaml/automl.pyindex d9f44f9d6..baa77ef98 100644--- a/flaml/automl.py+++ b/flaml/automl.py@@ -655,9 +655,9 @@ class AutoML:and self.X_val is None)self.sample = sample and (eval_method != 'cv')if 'auto' == metric:- if 'binary' in task:+ if 'binary' in self.task:metric = 'roc_auc'- elif 'multi' in task:+ elif 'multi' in self.task:metric = 'log_loss'else:metric = 'r2'diff --git a/flaml/ml.py b/flaml/ml.pyindex ec927d1da..e198b0d35 100644--- a/flaml/ml.py+++ b/flaml/ml.py@@ -92,7 +92,10 @@ def get_y_pred(estimator, X, eval_metric, obj):elif eval_metric in ['log_loss', 'roc_auc']:y_pred = estimator.predict_proba(X)else:- y_pred = estimator.predict(X)+ try:+ y_pred = estimator.predict(X)+ except:+ y_pred = np.ones(X.shape[0])return y_preddiff --git a/flaml/training_log.py b/flaml/training_log.pyindex 8ad5fb3fb..6de6831b4 100644--- a/flaml/training_log.py+++ b/flaml/training_log.py@@ -44,6 +44,9 @@ class TrainingLogRecord(object):d = json.loads(json_str)return cls(**d)+ def __str__(self):+ return json.dumps(vars(self))+class TrainingLogCheckPoint(TrainingLogRecord):diff --git a/flaml/version.py b/flaml/version.pyindex 40692a7a9..b81b15805 100644--- a/flaml/version.py+++ b/flaml/version.py@@ -1 +1 @@-__version__="0.1.0"+__version__="0.1.1"diff --git a/settings.json b/settings.jsondeleted file mode 100644index b9d92de39..000000000--- a/settings.json+++ /dev/null@@ -1,4 +0,0 @@-{- "keep_max_logfiles": 30,- "logging_level": "info"-}\ No newline at end of filediff --git a/test/test_automl.py b/test/test_automl.pyindex 1c0269abf..8a51da97e 100644--- a/test/test_automl.py+++ b/test/test_automl.py@@ -100,11 +100,10 @@ class TestAutoML(unittest.TestCase):"model_history": True}X_train, y_train = load_boston(return_X_y=True)- n = len(y_train)- automl_experiment.fit(X_train=X_train[:n >> 1], y_train=y_train[:n >> 1],- X_val=X_train[n >> 1:], y_val=y_train[n >> 1:],+ n = int(len(y_train)*9//10)+ automl_experiment.fit(X_train=X_train[:n], y_train=y_train[:n],+ X_val=X_train[n:], y_val=y_train[n:],**automl_settings)- assert automl_experiment.y_val.shape[0] == n - (n >> 1)assert automl_experiment.eval_method == 'holdout'print(automl_experiment.predict(X_train))print(automl_experiment.model)diff --git a/test/test_python_log.py b/test/test_python_log.pynew file mode 100644index 000000000..561de54fd--- /dev/null+++ b/test/test_python_log.py@@ -0,0 +1,45 @@+from flaml import AutoML+from sklearn.datasets import load_boston+import os+import unittest+import logging+import tempfile+import io+++class TestLogging(unittest.TestCase):++ def test_logging_level(self):++ from flaml import logger, logger_formatter++ with tempfile.TemporaryDirectory() as d:++ training_log = os.path.join(d, "training.log")++ # Configure logging for the FLAML logger+ # and add a handler that outputs to a buffer.+ logger.setLevel(logging.INFO)+ buf = io.StringIO()+ ch = logging.StreamHandler(buf)+ ch.setFormatter(logger_formatter)+ logger.addHandler(ch)++ # Run a simple job.+ automl_experiment = AutoML()+ automl_settings = {+ "time_budget": 2,+ "metric": 'mse',+ "task": 'regression',+ "log_file_name": training_log,+ "log_training_metric": True,+ "model_history": True+ }+ X_train, y_train = load_boston(return_X_y=True)+ n = len(y_train)+ automl_experiment.fit(X_train=X_train[:n >> 1], y_train=y_train[:n >> 1],+ X_val=X_train[n >> 1:], y_val=y_train[n >> 1:],+ **automl_settings)++ # Check if the log buffer is populated.+ self.assertTrue(len(buf.getvalue()) > 0)diff --git a/test/test_split.py b/test/test_split.pyindex 77903f259..058fac489 100644--- a/test/test_split.py+++ b/test/test_split.py@@ -32,12 +32,7 @@ def _test(split_type):print(acc)--def test_stratified():- _test(split_type="stratified")---def test_uniform():+def _test_uniform():_test(split_type="uniform")diff --git a/test/test_training_log.py b/test/test_training_log.pynew file mode 100644index 000000000..2ac9f2b68--- /dev/null+++ b/test/test_training_log.py@@ -0,0 +1,41 @@+import os+import unittest+import logging+import json+from tempfile import TemporaryDirectory++from sklearn.datasets import load_boston++from flaml import AutoML+from flaml.training_log import training_log_reader+++class TestTrainingLog(unittest.TestCase):++ def test_training_log(self):++ with TemporaryDirectory() as d:+ filename = os.path.join(d, 'test_training_log.log')++ # Run a simple job.+ automl_experiment = AutoML()+ automl_settings = {+ "time_budget": 2,+ "metric": 'mse',+ "task": 'regression',+ "log_file_name": filename,+ "log_training_metric": True,+ "model_history": True+ }+ X_train, y_train = load_boston(return_X_y=True)+ automl_experiment.fit(X_train=X_train, y_train=y_train,+ **automl_settings)++ # Check if the training log file is populated.+ self.assertTrue(os.path.exists(filename))+ with training_log_reader(filename) as reader:+ count = 0+ for record in reader.records():+ print(record)+ count += 1+ self.assertGreater(count, 0)