{"cells": [{"metadata": {}, "cell_type": "markdown", "source": "![image](https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/notebooks/headers/AutoAI-Banner_Pipeline-Notebook.png)\n# Pipeline 12 Notebook - AutoAI Notebook v1.14.5\n\nConsider these tips for working with an auto-generated notebook:\n- Notebook code generated using AutoAI will execute successfully. If you modify the notebook, we cannot guarantee it will run successfully.\n- This pipeline is optimized for the original data set. The pipeline might fail or produce sub-optimum results if used with different data. If you want to use a different data set, consider retraining the AutoAI experiment to generate a new pipeline. For more information, see Cloud Platform \n- Before modifying the pipeline or trying to re-fit the pipeline, consider that the code converts dataframes to numpy arrays before fitting the pipeline (a current restriction of the preprocessor pipeline).\n"}, {"metadata": {}, "cell_type": "markdown", "source": "\n## Notebook content\n\nThis notebook contains a Scikit-learn representation of AutoAI pipeline. This notebook introduces commands for getting data, training the model, and testing the model. \n\nSome familiarity with Python is helpful. This notebook uses Python 3.7 and scikit-learn 0.23.1."}, {"metadata": {"pycharm": {"name": "#%% md\n"}}, "cell_type": "markdown", "source": "## Notebook goals\n\n- Scikit-learn pipeline definition\n- Pipeline training \n- Pipeline evaluation\n\n## Contents\n\nThis notebook contains the following parts:\n\n**[Setup](#setup)**
\n  [Package installation](#install)
\n  [AutoAI experiment metadata](#variables_definition)
\n**[Pipeline inspection](#inspection)**
\n  [Read training data](#read)
\n  [Train and test data split](#split)
\n  [Make pipeline](#preview_model_to_python_code)
\n  [Train pipeline model](#train)
\n  [Test pipeline model](#test_model)
\n**[Next steps](#next_steps)**
\n**[Copyrights](#copyrights)**"}, {"metadata": {}, "cell_type": "markdown", "source": "\n# Setup"}, {"metadata": {}, "cell_type": "markdown", "source": "\n## Package installation\nBefore you use the sample code in this notebook, install the following packages:\n - ibm_watson_machine_learning,\n - autoai-libs.\n"}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:00:45.009458Z", "iopub.status.busy": "2020-10-12T14:00:45.007968Z", "iopub.status.idle": "2020-10-12T14:00:46.037702Z", "shell.execute_reply": "2020-10-12T14:00:46.038270Z"}, "pycharm": {"name": "#%%\n"}, "scrolled": true}, "cell_type": "code", "source": "!pip install ibm-watson-machine-learning | tail -n 1\n!pip install -U autoai-libs==1.12.5 | tail -n 1", "execution_count": 1, "outputs": [{"output_type": "stream", "text": "/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/dhcrypto.py:16: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\n/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/util.py:25: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\nRequirement already satisfied: docutils<0.16,>=0.10 in /opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages (from ibm-cos-sdk-core==2.7.0->ibm-cos-sdk==2.7.*->ibm-watson-machine-learning) (0.15.2)\n/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/dhcrypto.py:16: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\n/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/secretstorage/util.py:25: CryptographyDeprecationWarning: int_from_bytes is deprecated, use int.from_bytes instead\n from cryptography.utils import int_from_bytes\nSuccessfully installed autoai-libs-1.12.5 gensim-3.8.3 smart-open-5.0.0\n", "name": "stdout"}]}, {"metadata": {}, "cell_type": "markdown", "source": "\n## AutoAI experiment metadata\nThe following cell contains the training data connection details. \n**Note**: The connection might contain authorization credentials, so be careful when sharing the notebook."}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:00:49.797633Z", "iopub.status.busy": "2020-10-12T14:00:49.796778Z", "iopub.status.idle": "2020-10-12T14:00:57.182715Z", "shell.execute_reply": "2020-10-12T14:00:57.183132Z"}, "pycharm": {"is_executing": true}}, "cell_type": "code", "source": "# @hidden_cell\nfrom ibm_watson_machine_learning.helpers import DataConnection\nfrom ibm_watson_machine_learning.helpers import S3Connection, S3Location\n\ntraining_data_reference = [DataConnection(\n connection=S3Connection(\n api_key='YLrM_K3seFDkiGkQU-XEQNKug3KY5zZ-E4r8kHu4S_Dk',\n auth_endpoint='https://iam.bluemix.net/oidc/token/',\n endpoint_url='https://s3.eu-geo.objectstorage.softlayer.net'\n ),\n location=S3Location(\n bucket='diabetesprediction-donotdelete-pr-am3iyq6p2ccof4',\n path='diabetes.csv'\n )),\n]\ntraining_result_reference = DataConnection(\n connection=S3Connection(\n api_key='YLrM_K3seFDkiGkQU-XEQNKug3KY5zZ-E4r8kHu4S_Dk',\n auth_endpoint='https://iam.bluemix.net/oidc/token/',\n endpoint_url='https://s3.eu-geo.objectstorage.softlayer.net'\n ),\n location=S3Location(\n bucket='diabetesprediction-donotdelete-pr-am3iyq6p2ccof4',\n path='auto_ml/6f1472e5-330e-45da-b5b8-6610bf8af6e3/wml_data/be48ec68-c597-464f-9532-3ad7f797302c/data/automl',\n model_location='auto_ml/6f1472e5-330e-45da-b5b8-6610bf8af6e3/wml_data/be48ec68-c597-464f-9532-3ad7f797302c/data/automl/hpo_c_output/Pipeline9/model.pickle',\n training_status='auto_ml/6f1472e5-330e-45da-b5b8-6610bf8af6e3/wml_data/be48ec68-c597-464f-9532-3ad7f797302c/training-status.json'\n ))", "execution_count": 2, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "Following cell contains input parameters provided to run the AutoAI experiment in Watson Studio."}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:00:57.187305Z", "iopub.status.busy": "2020-10-12T14:00:57.186602Z", "iopub.status.idle": "2020-10-12T14:00:57.188392Z", "shell.execute_reply": "2020-10-12T14:00:57.188878Z"}, "pycharm": {"name": "#%%\n"}}, "cell_type": "code", "source": "experiment_metadata = dict(\n prediction_type='classification',\n prediction_column='Outcome',\n holdout_size=0.1,\n scoring='accuracy',\n deployment_url='https://eu-gb.ml.cloud.ibm.com',\n csv_separator=',',\n random_state=33,\n max_number_of_estimators=3,\n daub_include_only_estimators=None,\n training_data_reference=training_data_reference,\n training_result_reference=training_result_reference,\n project_id='65580c8e-1337-47e1-a99a-c8efbc6885fd',\n positive_label=1\n)", "execution_count": 3, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "\n# Pipeline inspection"}, {"metadata": {"pycharm": {"name": "#%% md\n"}}, "cell_type": "markdown", "source": "\n## Read training data\n\nRetrieve training dataset from AutoAI experiment as pandas DataFrame."}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:01:16.076169Z", "iopub.status.busy": "2020-10-12T14:01:16.075589Z", "iopub.status.idle": "2020-10-12T14:01:19.190233Z", "shell.execute_reply": "2020-10-12T14:01:19.190807Z"}, "pycharm": {"is_executing": true, "name": "#%%\n"}}, "cell_type": "code", "source": "df = training_data_reference[0].read(csv_separator=experiment_metadata['csv_separator'])\ndf.dropna('rows', how='any', subset=[experiment_metadata['prediction_column']], inplace=True)", "execution_count": 4, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "\n## Train and test data split"}, {"metadata": {"pycharm": {"is_executing": true}}, "cell_type": "code", "source": "from sklearn.model_selection import train_test_split\n\ndf.drop_duplicates(inplace=True)\nX = df.drop([experiment_metadata['prediction_column']], axis=1).values\ny = df[experiment_metadata['prediction_column']].values\n\ntrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size=experiment_metadata['holdout_size'],\n stratify=y, random_state=experiment_metadata['random_state'])", "execution_count": 5, "outputs": []}, {"metadata": {"pycharm": {"name": "#%% md\n"}}, "cell_type": "markdown", "source": "\n## Make pipeline\nIn the next cell, you can find the Scikit-learn definition of the selected AutoAI pipeline."}, {"metadata": {}, "cell_type": "markdown", "source": "Import statements."}, {"metadata": {"pycharm": {"is_executing": true, "name": "#%%\n"}}, "cell_type": "code", "source": "from autoai_libs.transformers.exportable import NumpyColumnSelector\nfrom autoai_libs.transformers.exportable import CompressStrings\nfrom autoai_libs.transformers.exportable import NumpyReplaceMissingValues\nfrom autoai_libs.transformers.exportable import NumpyReplaceUnknownValues\nfrom autoai_libs.transformers.exportable import boolean2float\nfrom autoai_libs.transformers.exportable import CatImputer\nfrom autoai_libs.transformers.exportable import CatEncoder\nimport numpy as np\nfrom autoai_libs.transformers.exportable import float32_transform\nfrom sklearn.pipeline import make_pipeline\nfrom autoai_libs.transformers.exportable import FloatStr2Float\nfrom autoai_libs.transformers.exportable import NumImputer\nfrom autoai_libs.transformers.exportable import OptStandardScaler\nfrom sklearn.pipeline import make_union\nfrom autoai_libs.transformers.exportable import NumpyPermuteArray\nfrom autoai_libs.cognito.transforms.transform_utils import TAM\nfrom sklearn.decomposition import PCA\nfrom autoai_libs.cognito.transforms.transform_utils import FS1\nfrom autoai_libs.cognito.transforms.transform_utils import TA1\nimport autoai_libs.utils.fc_methods\nfrom sklearn.linear_model import LogisticRegression", "execution_count": 6, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "#### Pre-processing & Estimator."}, {"metadata": {"pycharm": {"is_executing": true, "name": "#%%\n"}}, "cell_type": "code", "source": "numpy_column_selector_0 = NumpyColumnSelector(columns=[0, 2, 3, 7])\ncompress_strings = CompressStrings(\n compress_type=\"hash\",\n dtypes_list=[\n \"float_int_num\",\n \"float_int_num\",\n \"float_int_num\",\n \"float_int_num\",\n ],\n missing_values_reference_list=[\"\", \"-\", \"?\", float(\"nan\")],\n misslist_list=[[], [], [], []],\n)\nnumpy_replace_missing_values_0 = NumpyReplaceMissingValues(\n missing_values=[], filling_values=100001\n)\nnumpy_replace_unknown_values = NumpyReplaceUnknownValues(\n filling_values=100001,\n filling_values_list=[100001, 100001, 100001, 100001],\n missing_values_reference_list=[\"\", \"-\", \"?\", float(\"nan\")],\n)\ncat_imputer = CatImputer(\n strategy=\"most_frequent\",\n missing_values=100001,\n sklearn_version_family=\"23\",\n)\ncat_encoder = CatEncoder(\n encoding=\"ordinal\",\n categories=\"auto\",\n dtype=np.float64,\n handle_unknown=\"error\",\n sklearn_version_family=\"23\",\n)\npipeline_0 = make_pipeline(\n numpy_column_selector_0,\n compress_strings,\n numpy_replace_missing_values_0,\n numpy_replace_unknown_values,\n boolean2float(),\n cat_imputer,\n cat_encoder,\n float32_transform(),\n)\nnumpy_column_selector_1 = NumpyColumnSelector(columns=[1, 4, 5, 6])\nfloat_str2_float = FloatStr2Float(\n dtypes_list=[\"float_int_num\", \"float_int_num\", \"float_num\", \"float_num\"],\n missing_values_reference_list=[],\n)\nnumpy_replace_missing_values_1 = NumpyReplaceMissingValues(\n missing_values=[], filling_values=float(\"nan\")\n)\nnum_imputer = NumImputer(strategy=\"median\", missing_values=float(\"nan\"))\nopt_standard_scaler = OptStandardScaler(\n num_scaler_copy=None,\n num_scaler_with_mean=None,\n num_scaler_with_std=None,\n use_scaler_flag=False,\n)\npipeline_1 = make_pipeline(\n numpy_column_selector_1,\n float_str2_float,\n numpy_replace_missing_values_1,\n num_imputer,\n opt_standard_scaler,\n float32_transform(),\n)\nunion = make_union(pipeline_0, pipeline_1)\nnumpy_permute_array = NumpyPermuteArray(\n axis=0, permutation_indices=[0, 2, 3, 7, 1, 4, 5, 6]\n)\ntam = TAM(\n tans_class=PCA(),\n name=\"pca\",\n col_names=[\n \"Pregnancies\",\n \"Glucose\",\n \"BloodPressure\",\n \"SkinThickness\",\n \"Insulin\",\n \"BMI\",\n \"DiabetesPedigreeFunction\",\n \"Age\",\n ],\n col_dtypes=[\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n ],\n)\nfs1_0 = FS1(\n cols_ids_must_keep=range(0, 8),\n additional_col_count_to_keep=8,\n ptype=\"classification\",\n)\nta1 = TA1(\n fun=np.sqrt,\n name=\"sqrt\",\n datatypes=[\"numeric\"],\n feat_constraints=[\n autoai_libs.utils.fc_methods.is_non_negative,\n autoai_libs.utils.fc_methods.is_not_categorical,\n ],\n col_names=[\n \"Pregnancies\",\n \"Glucose\",\n \"BloodPressure\",\n \"SkinThickness\",\n \"Insulin\",\n \"BMI\",\n \"DiabetesPedigreeFunction\",\n \"Age\",\n \"pca_0\",\n \"pca_1\",\n \"pca_2\",\n \"pca_3\",\n \"pca_4\",\n \"pca_5\",\n \"pca_6\",\n \"pca_7\",\n ],\n col_dtypes=[\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n np.dtype(\"float32\"),\n ],\n)\nfs1_1 = FS1(\n cols_ids_must_keep=range(0, 8),\n additional_col_count_to_keep=8,\n ptype=\"classification\",\n)\nlogistic_regression = LogisticRegression(\n class_weight=\"balanced\",\n dual=True,\n fit_intercept=False,\n intercept_scaling=0.001256138140153018,\n max_iter=948,\n n_jobs=1,\n random_state=33,\n solver=\"liblinear\",\n tol=7.890895594583663e-05,\n)\n", "execution_count": 7, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "Pipeline."}, {"metadata": {"pycharm": {"is_executing": true, "name": "#%%\n"}}, "cell_type": "code", "source": "pipeline = make_pipeline(\n union, numpy_permute_array, tam, fs1_0, ta1, fs1_1, logistic_regression\n)", "execution_count": 8, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "\n## Train pipeline model\n"}, {"metadata": {}, "cell_type": "markdown", "source": "### Define scorer from the optimization metric\nThis cell constructs the cell scorer based on the experiment metadata."}, {"metadata": {"pycharm": {"is_executing": true}}, "cell_type": "code", "source": "from sklearn.metrics import get_scorer\n\nscorer = get_scorer(experiment_metadata['scoring'])", "execution_count": 9, "outputs": []}, {"metadata": {"pycharm": {"name": "#%% md\n"}}, "cell_type": "markdown", "source": "\n### Fit pipeline model\nIn this cell, the pipeline is fitted."}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:01:19.291734Z", "iopub.status.busy": "2020-10-12T14:01:19.244735Z", "iopub.status.idle": "2020-10-12T14:01:19.338461Z", "shell.execute_reply": "2020-10-12T14:01:19.338958Z"}, "pycharm": {"is_executing": true, "name": "#%%\n"}, "scrolled": true}, "cell_type": "code", "source": "pipeline.fit(train_X,train_y)", "execution_count": 10, "outputs": [{"output_type": "execute_result", "execution_count": 10, "data": {"text/plain": "Pipeline(steps=[('featureunion',\n FeatureUnion(transformer_list=[('pipeline-1',\n Pipeline(steps=[('numpycolumnselector',\n NumpyColumnSelector(columns=[0,\n 2,\n 3,\n 7])),\n ('compressstrings',\n CompressStrings(compress_type='hash',\n dtypes_list=['float_int_num',\n 'float_int_num',\n 'float_int_num',\n 'float_int_num'],\n missing_values_reference_list=['',\n '-',\n '?',\n nan],\n misslist_list...\n autoai_libs.cognito.transforms.transform_utils.FS1(cols_ids_must_keep = range(0, 8), additional_col_count_to_keep = 8, ptype = 'classification')),\n ('logisticregression',\n LogisticRegression(class_weight='balanced', dual=True,\n fit_intercept=False,\n intercept_scaling=0.001256138140153018,\n max_iter=948, n_jobs=1, random_state=33,\n solver='liblinear',\n tol=7.890895594583663e-05))])"}, "metadata": {}}]}, {"metadata": {}, "cell_type": "markdown", "source": "\n## Test pipeline model"}, {"metadata": {}, "cell_type": "markdown", "source": "Score the fitted pipeline with the generated scorer using the holdout dataset."}, {"metadata": {"execution": {"iopub.execute_input": "2020-10-12T14:02:03.910267Z", "iopub.status.busy": "2020-10-12T14:02:03.909710Z", "iopub.status.idle": "2020-10-12T14:02:03.914154Z", "shell.execute_reply": "2020-10-12T14:02:03.914727Z"}, "pycharm": {"is_executing": true, "name": "#%%\n"}}, "cell_type": "code", "source": "score = scorer(pipeline, test_X, test_y)\nprint(score)", "execution_count": 11, "outputs": [{"output_type": "stream", "text": "0.7532467532467533\n", "name": "stdout"}]}, {"metadata": {}, "cell_type": "markdown", "source": "\n# Next steps\n\n#### [Model deployment as webservice](https://github.com/IBM/watson-machine-learning-samples/tree/master/cloud/notebooks/python_sdk/deployments/autoai)\n#### [Run AutoAI experiment with python SDK](https://github.com/IBM/watson-machine-learning-samples/tree/master/cloud/notebooks/python_sdk/experiments/autoai) "}, {"metadata": {}, "cell_type": "markdown", "source": "## Deploy and Score\nIn this section you will learn how to deploy and score pipeline model as webservice using WML instance.\n\n\n## Connection to WML\nAuthenticate the Watson Machine Learning service on IBM Cloud.\n\nTip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below.\n\nNote: You can also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below.\n\nAction: Enter your api_key in the following cell."}, {"metadata": {}, "cell_type": "code", "source": "api_key = \"QRPgKROIhFZE6KaYwvm-jhIHPQfAYoAUZE9-_1s0sWbj\"\n\nwml_credentials = {\n \"apikey\": api_key,\n \"url\": experiment_metadata[\"deployment_url\"]\n}", "execution_count": 12, "outputs": []}, {"metadata": {}, "cell_type": "markdown", "source": "## Create deployment\nAction: If you want to deploy refined pipeline please change the pipeline_model to new_pipeline. If you prefer you can also change the deployment_name. To perform deployment please specify target_space_id"}, {"metadata": {}, "cell_type": "code", "source": "target_space_id = \"f2f33a84-ecdd-498b-b7b8-fae6ce42026c\"\npipeline_name = \"Diabetes_predictor_4m_nbk\"\n\nfrom ibm_watson_machine_learning.deployment import WebService\nservice = WebService(target_wml_credentials=wml_credentials,\n target_space_id=target_space_id)\nservice.create(\nmodel=pipeline,\nmetadata=experiment_metadata,\ndeployment_name=f'{pipeline_name}_webservice'\n)", "execution_count": 28, "outputs": [{"output_type": "stream", "text": "Preparing an AutoAI Deployment...\nDepreciation Warning: Passing an object will no longer be supported. Please specify the AutoAI model name to deploy.\nPublished model uid: 9dc5b7d2-67bb-47e4-9838-dd68a1257023\nDeploying model 9dc5b7d2-67bb-47e4-9838-dd68a1257023 using V4 client.\n\n\n#######################################################################################\n\nSynchronous deployment creation for uid: '9dc5b7d2-67bb-47e4-9838-dd68a1257023' started\n\n#######################################################################################\n\n\ninitializing.........\nready\n\n\n------------------------------------------------------------------------------------------------\nSuccessfully finished deployment creation, deployment_uid='4e04fa53-ab66-4cab-a749-3739fb6ae7a4'\n------------------------------------------------------------------------------------------------\n\n\n", "name": "stdout"}]}, {"metadata": {}, "cell_type": "markdown", "source": "Deployment object could be printed to show basic information:"}, {"metadata": {}, "cell_type": "code", "source": "print(service)", "execution_count": 29, "outputs": [{"output_type": "stream", "text": "name: Diabetes_predictor_4m_nbk_webservice, id: 4e04fa53-ab66-4cab-a749-3739fb6ae7a4, scoring_url: https://eu-gb.ml.cloud.ibm.com/ml/v4/deployments/4e04fa53-ab66-4cab-a749-3739fb6ae7a4/predictions, asset_id: 9dc5b7d2-67bb-47e4-9838-dd68a1257023\n", "name": "stdout"}]}, {"metadata": {}, "cell_type": "markdown", "source": "To be able to show all available information about deployment use .get_params() method:"}, {"metadata": {}, "cell_type": "code", "source": "service.get_params()", "execution_count": 30, "outputs": [{"output_type": "execute_result", "execution_count": 30, "data": {"text/plain": "{'entity': {'asset': {'id': '9dc5b7d2-67bb-47e4-9838-dd68a1257023'},\n 'custom': {},\n 'deployed_asset_type': 'model',\n 'hardware_spec': {'id': 'c076e82c-b2a7-4d20-9c0f-1f0c2fdf5a24',\n 'name': 'M',\n 'num_nodes': 1},\n 'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S',\n 'num_nodes': 1},\n 'node_runtime_id': 'auto_ai.kb'}],\n 'name': 'Diabetes_predictor_4m_nbk_webservice',\n 'online': {},\n 'space_id': 'f2f33a84-ecdd-498b-b7b8-fae6ce42026c',\n 'status': {'online_url': {'url': 'https://eu-gb.ml.cloud.ibm.com/ml/v4/deployments/4e04fa53-ab66-4cab-a749-3739fb6ae7a4/predictions'},\n 'state': 'ready'}},\n 'metadata': {'created_at': '2021-04-23T06:25:36.630Z',\n 'id': '4e04fa53-ab66-4cab-a749-3739fb6ae7a4',\n 'modified_at': '2021-04-23T06:25:36.630Z',\n 'name': 'Diabetes_predictor_4m_nbk_webservice',\n 'owner': 'IBMid-55000A1BBE',\n 'space_id': 'f2f33a84-ecdd-498b-b7b8-fae6ce42026c'}}"}, "metadata": {}}]}, {"metadata": {}, "cell_type": "markdown", "source": "## Score webservice:\n\nYou can make scoring request by calling score() on deployed pipeline."}, {"metadata": {}, "cell_type": "code", "source": "test_df = df.sample(n=5).drop([experiment_metadata['prediction_column']], axis=1)", "execution_count": 31, "outputs": []}, {"metadata": {}, "cell_type": "code", "source": "print(test_df)", "execution_count": 32, "outputs": [{"output_type": "stream", "text": " Pregnancies Glucose BloodPressure SkinThickness Insulin BMI \\\n374 2 122 52 43 158 36.2 \n709 2 93 64 32 160 38.0 \n15 7 100 0 0 0 30.0 \n441 2 83 66 23 50 32.2 \n185 7 194 68 28 0 35.9 \n\n DiabetesPedigreeFunction Age \n374 0.816 28 \n709 0.674 23 \n15 0.484 32 \n441 0.497 22 \n185 0.745 41 \n", "name": "stdout"}]}, {"metadata": {}, "cell_type": "code", "source": "predictions = service.score(payload=test_df)\npredictions", "execution_count": 33, "outputs": [{"output_type": "execute_result", "execution_count": 33, "data": {"text/plain": "{'predictions': [{'fields': ['prediction', 'probability'],\n 'values': [[0, [0.872248659031778, 0.1277513409682221]],\n [0, [0.9914757704779724, 0.00852422952202755]],\n [0, [0.6592459444179399, 0.34075405558206]],\n [0, [0.9962777515691374, 0.0037222484308625284]],\n [1, [0.006635051966327077, 0.9933649480336729]]]}]}"}, "metadata": {}}]}, {"metadata": {"pycharm": {"name": "#%% md\n"}}, "cell_type": "markdown", "source": "\n### Copyrights\n\nLicensed Materials - Copyright \u00a9 2021 IBM. This notebook and its source code are released under the terms of the ILAN License.\nUse, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n\n**Note:** The auto-generated notebooks are subject to the International License Agreement for Non-Warranted Programs \n(or equivalent) and License Information document for Watson Studio Auto-generated Notebook (License Terms), \nsuch agreements located in the link below. Specifically, the Source Components and Sample Materials clause \nincluded in the License Information document for Watson Studio Auto-generated Notebook applies to the auto-generated notebooks. \n\nBy downloading, copying, accessing, or otherwise using the materials, you agree to the License Terms\n\n___"}], "metadata": {"kernelspec": {"name": "python3", "display_name": "Python 3.7", "language": "python"}, "language_info": {"name": "python", "version": "3.7.10", "mimetype": "text/x-python", "codemirror_mode": {"name": "ipython", "version": 3}, "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "file_extension": ".py"}}, "nbformat": 4, "nbformat_minor": 2}