Skip to content

Commit ef7d4f8

Browse files
authored
ipython bugfix (#1301)
1 parent b810e37 commit ef7d4f8

File tree

28 files changed

+460
-447
lines changed

28 files changed

+460
-447
lines changed

.github/workflows/run-forecast-explainer-tests.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ jobs:
4646
- uses: ./.github/workflows/set-dummy-conf
4747
name: "Test config setup"
4848

49+
- name: Free up disk space
50+
run: |
51+
sudo apt-get clean
52+
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
53+
df -h
54+
4955
- name: "Run Forecast Explainer Tests"
5056
timeout-minutes: 180
5157
shell: bash

ads/automl/provider.py

Lines changed: 32 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,33 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; -*-
32

4-
# Copyright (c) 2020, 2023 Oracle and/or its affiliates.
3+
# Copyright (c) 2020, 2025 Oracle and/or its affiliates.
54
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
65

76
import logging
8-
import time
97
import sys
8+
import time
109
import warnings
11-
from abc import ABC, abstractmethod, abstractproperty
12-
import math
13-
import pandas as pd
10+
from abc import ABC, abstractmethod
11+
12+
import matplotlib.pyplot as plt
1413
import numpy as np
14+
import pandas as pd
1515
from sklearn import set_config
1616
from sklearn.dummy import DummyClassifier, DummyRegressor
1717

18-
import matplotlib.pyplot as plt
19-
2018
import ads
19+
from ads.common import logger, utils
20+
from ads.common.decorator.deprecate import deprecated
21+
from ads.common.decorator.runtime_dependency import (
22+
OptionalDependency,
23+
runtime_dependency,
24+
)
2125
from ads.common.utils import (
26+
is_notebook,
2227
ml_task_types,
2328
wrap_lines,
24-
is_documentation_mode,
25-
is_notebook,
2629
)
27-
from ads.common.decorator.runtime_dependency import (
28-
runtime_dependency,
29-
OptionalDependency,
30-
)
31-
from ads.common.decorator.deprecate import deprecated
3230
from ads.dataset.label_encoder import DataFrameLabelEncoder
33-
from ads.dataset.helper import is_text_data
34-
35-
from ads.common import logger, utils
3631

3732

3833
class AutoMLProvider(ABC):
@@ -141,7 +136,7 @@ def get_transformer_pipeline(self):
141136
pass
142137

143138

144-
class BaselineModel(object):
139+
class BaselineModel:
145140
"""
146141
A BaselineModel object that supports fit/predict/predict_proba/transform
147142
interface. Labels (y) are encoded using DataFrameLabelEncoder.
@@ -156,7 +151,6 @@ def __init__(self, est):
156151
self.df_label_encoder = DataFrameLabelEncoder()
157152

158153
def predict(self, X):
159-
160154
"""
161155
Runs the Baselines predict function and returns the result.
162156
@@ -174,7 +168,6 @@ def predict(self, X):
174168
return self.est.predict(X)
175169

176170
def predict_proba(self, X):
177-
178171
"""
179172
Runs the Baselines predict_proba function and returns the result.
180173
@@ -192,7 +185,6 @@ def predict_proba(self, X):
192185
return self.est.predict_proba(X)
193186

194187
def fit(self, X, y):
195-
196188
"""
197189
Fits the baseline estimator.
198190
@@ -213,7 +205,6 @@ def fit(self, X, y):
213205
return self
214206

215207
def transform(self, X):
216-
217208
"""
218209
Runs the Baselines transform function and returns the result.
219210
@@ -304,16 +295,15 @@ def decide_estimator(self, **kwargs):
304295
"""
305296
if self.est is not None:
306297
return self.est
307-
else:
308-
if self.ml_task_type == ml_task_types.REGRESSION:
309-
return BaselineModel(DummyRegressor())
310-
elif self.ml_task_type in [
311-
ml_task_types.BINARY_CLASSIFICATION,
312-
ml_task_types.MULTI_CLASS_CLASSIFICATION,
313-
ml_task_types.BINARY_TEXT_CLASSIFICATION,
314-
ml_task_types.MULTI_CLASS_TEXT_CLASSIFICATION,
315-
]:
316-
return BaselineModel(DummyClassifier())
298+
elif self.ml_task_type == ml_task_types.REGRESSION:
299+
return BaselineModel(DummyRegressor())
300+
elif self.ml_task_type in [
301+
ml_task_types.BINARY_CLASSIFICATION,
302+
ml_task_types.MULTI_CLASS_CLASSIFICATION,
303+
ml_task_types.BINARY_TEXT_CLASSIFICATION,
304+
ml_task_types.MULTI_CLASS_TEXT_CLASSIFICATION,
305+
]:
306+
return BaselineModel(DummyClassifier())
317307

318308

319309
# An installation of oracle labs automl is required only for this class
@@ -483,8 +473,11 @@ def print_summary(
483473
0, "Rank based on Performance", np.arange(2, len(sorted_summary_df) + 2)
484474
)
485475

486-
from IPython.core.display import display, HTML
476+
from IPython.display import HTML
487477

478+
from ads.common.utils import get_display
479+
480+
display = get_display()
488481
with pd.option_context(
489482
"display.max_colwidth",
490483
1000,
@@ -595,9 +588,7 @@ def _decide_estimator(self, **kwargs):
595588
if (
596589
self.ml_task_type == ml_task_types.BINARY_CLASSIFICATION
597590
or self.ml_task_type == ml_task_types.BINARY_TEXT_CLASSIFICATION
598-
):
599-
test_model_list = ["LogisticRegression"]
600-
elif (
591+
) or (
601592
self.ml_task_type == ml_task_types.MULTI_CLASS_CLASSIFICATION
602593
or self.ml_task_type == ml_task_types.MULTI_CLASS_TEXT_CLASSIFICATION
603594
):
@@ -712,7 +703,7 @@ def visualize_algorithm_selection_trials(self, ylabel=None):
712703
for f in mean_scores_ser.keys():
713704
se = scipy.stats.sem(scores_ser[f], ddof=1)
714705
y_error.append(se)
715-
if f == "{}_AS".format(self.est.selected_model_):
706+
if f == f"{self.est.selected_model_}_AS":
716707
colors.append("orange")
717708
elif mean_scores_ser[f] >= mean_scores_ser.mean():
718709
colors.append("teal")
@@ -741,7 +732,7 @@ def visualize_adaptive_sampling_trials(self):
741732
_log_visualize_no_trials("adaptive sampling")
742733
return
743734
fig, ax = plt.subplots(1, figsize=(6, 3))
744-
ax.set_title("Adaptive Sampling ({})".format(trials[0][0]))
735+
ax.set_title(f"Adaptive Sampling ({trials[0][0]})")
745736
ax.set_xlabel("Dataset sample size")
746737
ax.set_ylabel(r"Predicted model score")
747738
scores = [
@@ -882,7 +873,7 @@ def visualize_tuning_trials(self, ylabel=None):
882873
plt.show()
883874

884875

885-
class AutoMLPreprocessingTransformer(object): # pragma: no cover
876+
class AutoMLPreprocessingTransformer: # pragma: no cover
886877
@deprecated(
887878
details="Working with AutoML has moved from within ADS to working directly with the AutoMLx library. AutoMLx are preinstalled in conda pack automlx_p38_cpu_v2 and later, and can now be updated independently of ADS. AutoMLx documentation may be found at https://docs.oracle.com/en-us/iaas/tools/automlx/latest/html/multiversion/v23.1.1/index.html. Notebook examples are in Oracle's samples repository: https://github.com/oracle-samples/oci-data-science-ai-samples/tree/master/notebook_examples and a migration tutorial can be found at https://accelerated-data-science.readthedocs.io/en/latest/user_guide/model_training/automl/quick_start.html .",
888879
raise_error=True,
@@ -931,7 +922,7 @@ def __repr__(self):
931922
return self.msg
932923

933924

934-
class AutoMLFeatureSelection(object): # pragma: no cover
925+
class AutoMLFeatureSelection: # pragma: no cover
935926
@deprecated(
936927
details="Working with AutoML has moved from within ADS to working directly with the AutoMLx library. AutoMLx are preinstalled in conda pack automlx_p38_cpu_v2 and later, and can now be updated independently of ADS. AutoMLx documentation may be found at https://docs.oracle.com/en-us/iaas/tools/automlx/latest/html/multiversion/v23.1.1/index.html. Notebook examples are in Oracle's samples repository: https://github.com/oracle-samples/oci-data-science-ai-samples/tree/master/notebook_examples and a migration tutorial can be found at https://accelerated-data-science.readthedocs.io/en/latest/user_guide/model_training/automl/quick_start.html .",
937928
raise_error=True,

ads/catalog/model.py

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; -*-
32

4-
# Copyright (c) 2020, 2024 Oracle and/or its affiliates.
3+
# Copyright (c) 2020, 2025 Oracle and/or its affiliates.
54
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
65

76
import warnings
@@ -27,20 +26,30 @@
2726

2827
import pandas as pd
2928
import yaml
29+
from oci.data_science.data_science_client import DataScienceClient
30+
from oci.data_science.models import (
31+
ArtifactExportDetailsObjectStorage,
32+
ArtifactImportDetailsObjectStorage,
33+
CreateModelDetails,
34+
ExportModelArtifactDetails,
35+
ImportModelArtifactDetails,
36+
ModelSummary,
37+
WorkRequest,
38+
)
39+
from oci.data_science.models import Model as OCIModel
40+
from oci.data_science.models.model_provenance import ModelProvenance
41+
from oci.data_science.models.update_model_details import UpdateModelDetails
42+
from oci.exceptions import ServiceError
43+
from oci.identity import IdentityClient
44+
3045
from ads.catalog.summary import SummaryList
3146
from ads.common import auth, logger, oci_client, utils
3247
from ads.common.decorator.deprecate import deprecated
3348
from ads.common.decorator.runtime_dependency import (
34-
runtime_dependency,
3549
OptionalDependency,
50+
runtime_dependency,
3651
)
3752
from ads.common.model_artifact import ConflictStrategy, ModelArtifact
38-
from ads.model.model_metadata import (
39-
METADATA_SIZE_LIMIT,
40-
MetadataSizeTooLarge,
41-
ModelCustomMetadata,
42-
ModelTaxonomyMetadata,
43-
)
4453
from ads.common.object_storage_details import ObjectStorageDetails
4554
from ads.common.oci_resource import SEARCH_TYPE, OCIResource
4655
from ads.config import (
@@ -51,22 +60,14 @@
5160
)
5261
from ads.dataset.progress import TqdmProgressBar
5362
from ads.feature_engineering.schema import Schema
54-
from ads.model.model_version_set import ModelVersionSet, _extract_model_version_set_id
5563
from ads.model.deployment.model_deployer import ModelDeployer
56-
from oci.data_science.data_science_client import DataScienceClient
57-
from oci.data_science.models import (
58-
ArtifactExportDetailsObjectStorage,
59-
ArtifactImportDetailsObjectStorage,
60-
CreateModelDetails,
61-
ExportModelArtifactDetails,
62-
ImportModelArtifactDetails,
64+
from ads.model.model_metadata import (
65+
METADATA_SIZE_LIMIT,
66+
MetadataSizeTooLarge,
67+
ModelCustomMetadata,
68+
ModelTaxonomyMetadata,
6369
)
64-
from oci.data_science.models import Model as OCIModel
65-
from oci.data_science.models import ModelSummary, WorkRequest
66-
from oci.data_science.models.model_provenance import ModelProvenance
67-
from oci.data_science.models.update_model_details import UpdateModelDetails
68-
from oci.exceptions import ServiceError
69-
from oci.identity import IdentityClient
70+
from ads.model.model_version_set import ModelVersionSet, _extract_model_version_set_id
7071

7172
_UPDATE_MODEL_DETAILS_ATTRIBUTES = [
7273
"display_name",
@@ -391,8 +392,9 @@ def show_in_notebook(self, display_format: str = "dataframe") -> None:
391392
Nothing.
392393
"""
393394
if display_format == "dataframe":
394-
from IPython.core.display import display
395+
from ads.common.utils import get_display
395396

397+
display = get_display()
396398
display(self.to_dataframe())
397399
elif display_format == "yaml":
398400
print(self._to_yaml())
@@ -454,9 +456,9 @@ def commit(self, force: bool = True) -> None:
454456
if hasattr(self, "metadata_custom"):
455457
attributes["custom_metadata_list"] = self.metadata_custom._to_oci_metadata()
456458
if hasattr(self, "metadata_taxonomy"):
457-
attributes[
458-
"defined_metadata_list"
459-
] = self.metadata_taxonomy._to_oci_metadata()
459+
attributes["defined_metadata_list"] = (
460+
self.metadata_taxonomy._to_oci_metadata()
461+
)
460462

461463
update_model_details = UpdateModelDetails(**attributes)
462464
# freeform_tags=self._model.freeform_tags, defined_tags=self._model.defined_tags)
@@ -558,7 +560,7 @@ def load_model(
558560

559561
try:
560562
provenance_response = cls._get_provenance_metadata(ds_client, model_id)
561-
except Exception as e:
563+
except Exception:
562564
raise ValueError(
563565
f"Unable to fetch model provenance metadata for model {model_id}"
564566
)
@@ -1071,7 +1073,7 @@ def _download_large_artifact(
10711073
None
10721074
Nothing.
10731075
"""
1074-
progress.update(f"Importing model artifacts from model catalog")
1076+
progress.update("Importing model artifacts from model catalog")
10751077
self._import_model_artifact(model_id=model_id, bucket_uri=bucket_uri)
10761078

10771079
progress.update("Copying model artifacts to the artifact directory")
@@ -1360,7 +1362,7 @@ def upload_model(
13601362
raise ValueError("project_id needs to be specified.")
13611363
schema_file = os.path.join(model_artifact.artifact_dir, "schema.json")
13621364
if os.path.exists(schema_file):
1363-
with open(schema_file, "r") as schema:
1365+
with open(schema_file) as schema:
13641366
metadata = json.load(schema)
13651367
freeform_tags = {"problem_type": metadata["problem_type"]}
13661368

@@ -1475,7 +1477,7 @@ def _export_model_artifact(
14751477
3. Exports artifact from the user's object storage bucket to the system one.
14761478
"""
14771479
artifact_zip_path = self._prepare_model_artifact(model_artifact, progress)
1478-
progress.update(f"Copying model artifact to the Object Storage bucket")
1480+
progress.update("Copying model artifact to the Object Storage bucket")
14791481

14801482
try:
14811483
bucket_uri_file_name = os.path.basename(bucket_uri)

ads/catalog/notebook.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; -*-
32

4-
# Copyright (c) 2020, 2024 Oracle and/or its affiliates.
3+
# Copyright (c) 2020, 2025 Oracle and/or its affiliates.
54
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
65

76
import warnings
@@ -14,31 +13,31 @@
1413
stacklevel=2,
1514
)
1615

17-
from pandas import DataFrame
18-
import oci
16+
from types import MethodType
17+
1918
from oci.data_science.models import (
20-
NotebookSessionSummary,
21-
UpdateNotebookSessionDetails,
2219
CreateNotebookSessionDetails,
2320
NotebookSession,
2421
NotebookSessionConfigurationDetails,
22+
NotebookSessionSummary,
23+
UpdateNotebookSessionDetails,
2524
)
2625
from oci.exceptions import ServiceError
27-
from types import MethodType
26+
from pandas import DataFrame
2827

2928
from ads.catalog.summary import SummaryList
29+
from ads.common import auth as authutil
30+
from ads.common import oci_client as oc
3031
from ads.common import utils
3132
from ads.common.decorator.runtime_dependency import (
32-
runtime_dependency,
3333
OptionalDependency,
34+
runtime_dependency,
3435
)
35-
from ads.common import auth as authutil
36-
from ads.common import oci_client as oc
3736
from ads.config import (
38-
OCI_IDENTITY_SERVICE_ENDPOINT,
3937
NB_SESSION_COMPARTMENT_OCID,
40-
PROJECT_OCID,
38+
OCI_IDENTITY_SERVICE_ENDPOINT,
4139
OCI_ODSC_SERVICE_ENDPOINT,
40+
PROJECT_OCID,
4241
)
4342

4443
create_notebook_details_attributes = CreateNotebookSessionDetails().swagger_types.keys()
@@ -210,8 +209,9 @@ def show_in_notebook(notebook_self):
210209
"""
211210
Describe the project by showing it's properties
212211
"""
213-
from IPython.core.display import display
212+
from ads.common.utils import get_display
214213

214+
display = get_display()
215215
display(notebook_self)
216216

217217
def _repr_html_(notebook_self):

0 commit comments

Comments
 (0)