### Install sasctl from source Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Installs the latest development version of sasctl directly from its GitHub repository. ```Shell pip install git+https://github.com/sassoftware/python-sasctl ``` -------------------------------- ### Start Python REPL with SASCTL Installed via Tox Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Launches an interactive Python REPL within an environment where the sasctl package is already installed, using the specified Python interpreter. ```Shell $ tox -e pyXX-tests -- python ``` -------------------------------- ### Install sasctl Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md This snippet shows how to install the sasctl library using pip, the Python package installer. Ensure you have Python 3.6 or later installed. ```bash pip install sasctl ``` -------------------------------- ### Install python-sasctl Dependencies Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_git_integration_example.ipynb Installs the necessary libraries for using python-sasctl, including Session and pzmm. It also imports Path for handling file paths and getpass for secure password input. ```python from sasctl import Session, pzmm from pathlib import Path import getpass ``` -------------------------------- ### Install sasctl with optional dependencies Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Installs sasctl with specific optional dependencies like swat or kerberos, or all available dependencies. ```Shell pip install sasctl[swat] pip install sasctl[kerberos] pip install sasctl[all] ``` -------------------------------- ### Full Model Lifecycle with scikit-learn Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Demonstrates the complete lifecycle of models using scikit-learn, including training, registration, publishing, real-time scoring, and performance reporting. ```Python # Example demonstrating training, registration, publishing, and scoring # from sklearn.ensemble import RandomForestClassifier # from sasctl.utils import register_model, publish_model, score_model # Train a model # model = RandomForestClassifier() # model.fit(X_train, y_train) # Register the model # register_model(model, 'path/to/model.pkl', 'MyRFModel', 'scikit-learn') # Publish the model # publish_model('MyRFModel', 'MyModelPackage', 'ModelVersion') # Score data in real-time # results = score_model('MyModelPackage', 'ModelVersion', input_data) ``` -------------------------------- ### Install sasctl Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Installs the latest version of the sasctl package using pip. ```Shell pip install sasctl ``` -------------------------------- ### Get Help (CLI) Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Displays the help information for the sasctl command-line interface. ```Shell sasctl --help ``` -------------------------------- ### Run Tox for Development Tasks Source: https://github.com/sassoftware/python-sasctl/blob/master/CONTRIBUTING.md Use the Tox tool to automate common development tasks such as testing, linting, and building documentation. Tox manages virtual environments and installs required packages automatically. ```Shell tox ``` -------------------------------- ### Direct REST API Calls with sasctl Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Demonstrates making direct REST API calls over HTTP(S) to SAS microservices using sasctl for customized behavior or accessing unexposed functionality. ```Python import sasctl # Example of making a direct REST API call # response = sasctl.request('GET', '/modelManager/models') # print(response.json()) ``` -------------------------------- ### Register H2O.ai model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers an H2O.ai model in SAS Model Manager. This intermediate example uses the H2O.ai library for classification models. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained H2O.ai model # h2o_model = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Register the H2O.ai model # sas_manager.register_model(h2o_model, 'h2o_classification_model', 'h2o') print("Example for registering an H2O.ai model.") ``` -------------------------------- ### Generate requirements.json file Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Generates a requirements.json file containing the minimal dependencies needed to run a Python model. This is an intermediate-level task. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a Python model object or path # model_object = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Generate requirements.json # requirements_file_path = sas_manager.generate_requirements(model_object, 'requirements.json') print("Example for generating a requirements.json file.") ``` -------------------------------- ### Register scikit-learn binary classification model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a scikit-learn binary classification model in SAS Model Manager. This example is suitable for beginners and utilizes the scikit-learn library. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained scikit-learn binary classification model # model = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Register the model # sas_manager.register_model(model, 'binary_classification_model', 'scikit-learn') print("Example for registering scikit-learn binary classification model.") ``` -------------------------------- ### Create and update custom model KPIs Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Demonstrates how to create and update custom model parameters and KPIs within SAS Model Manager. This is an intermediate-level task. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have model information and KPI data # model_name = 'MyModel' # kpi_data = {'accuracy': 0.95, 'precision': 0.92} # Instantiate SasModelManager sas_manager = SasModelManager() # Create or update custom KPIs # sas_manager.update_model_kpis(model_name, kpi_data) print("Example for creating and updating custom model KPIs.") ``` -------------------------------- ### Register SAS deep learning model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Creates and registers a SAS deep learning model using the dlpy library. This beginner example is for models created with SAS algorithms. Note: May not work with Python 3.10+. ```Python import sasctl from sasctl.tasks import register_model # Assuming you have a dlpy model object and connection details # dlpy_model = ... # cas_connection = ... # Your CAS connection object # Register the SAS deep learning model # register_model(cas_connection, dlpy_model, 'SAS DL Model', 'deeplearning') print("Example for registering a SAS deep learning model.") ``` -------------------------------- ### Register scikit-learn regression model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a scikit-learn regression model in SAS Model Manager. This example is for beginners and uses the scikit-learn library. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained scikit-learn regression model # model = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Register the model # sas_manager.register_model(model, 'regression_model', 'scikit-learn') print("Example for registering scikit-learn regression model.") ``` -------------------------------- ### Register scikit-learn classification model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a classification model created from a scikit-learn algorithm in SAS Model Manager. This example is suitable for beginners. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained scikit-learn classification model # model = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Register the model # sas_manager.register_model(model, 'sklearn_classification_model', 'scikit-learn') print("Example for registering a scikit-learn classification model.") ``` -------------------------------- ### SASCTL Model Registration Setup Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_complete_model_example_MLFlow_sklearn.ipynb Imports necessary SASCTL modules (`pzmm`, `Session`) and `Path` for file system operations. This sets up the environment for registering MLflow models with SAS Model Manager. ```Python # Pathing support from pathlib import Path # sasctl interface for importing models import sasctl.pzmm as pzmm from sasctl import Session ``` -------------------------------- ### Register Models with Model Metrics Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Trains tree-based models using scikit-learn, registers them in SAS Model Manager, and generates model fit statistics and ROC/Lift charts using the pzmm module. ```Python # Example using pzmm for model metrics # from sasctl.pzmm import Pzmm # from sklearn.ensemble import GradientBoostingClassifier # Train models # model1 = GradientBoostingClassifier() # model1.fit(X1, y1) # model2 = GradientBoostingClassifier() # model2.fit(X2, y2) # Register models and generate metrics # pzmm = Pzmm() # pzmm.register_model(model1, 'model1.pkl', 'Model1', 'scikit-learn', metrics=True) # pzmm.register_model(model2, 'model2.pkl', 'Model2', 'scikit-learn', metrics=True) ``` -------------------------------- ### Register SAS regression model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a regression model created from a SAS algorithm in SAS Model Manager. This beginner example uses the SWAT library. ```Python import sasctl from sasctl.tasks import register_model # Assuming you have a SAS model file and connection details # sas_model_path = 'path/to/sas/model' # cas_connection = ... # Your CAS connection object # Register the SAS regression model # register_model(cas_connection, sas_model_path, 'SAS Regression Model', 'regression') print("Example for registering a SAS regression model.") ``` -------------------------------- ### Register Azure OpenAI GPT Model via REST API Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Leverages a GPT-3.5-Turbo model from Azure OpenAI in SAS Model Manager and SAS Intelligent Decisioning using REST API calls. ```Python # Example of registering an Azure OpenAI model using REST API calls # import sasctl # import json # model_payload = { # "name": "AzureOpenAI_GPT35", # "version": "1.0", # "description": "GPT-3.5-Turbo model from Azure OpenAI", # "modelType": "Python", # "files": [ # {"name": "model.py", "content": "...your model code..."} # ], # "properties": { # "azure_openai_endpoint": "YOUR_AZURE_ENDPOINT", # "azure_openai_key": "YOUR_AZURE_KEY" # } # } # response = sasctl.request('POST', '/modelManager/models', data=json.dumps(model_payload)) # print(response.json()) ``` -------------------------------- ### Display MLFlow Output Dictionary Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Displays the outputsDict, which contains information about the MLFlow model's outputs, useful for verification before SAS Model Manager import. ```Python outputsDict ``` -------------------------------- ### Register SAS classification model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a classification model created from a SAS algorithm in SAS Model Manager. This beginner example utilizes the SWAT library. ```Python import sasctl from sasctl.tasks import register_model # Assuming you have a SAS model file and connection details # sas_model_path = 'path/to/sas/model' # cas_connection = ... # Your CAS connection object # Register the SAS classification model # register_model(cas_connection, sas_model_path, 'SAS Classification Model', 'classification') print("Example for registering a SAS classification model.") ``` -------------------------------- ### Register scikit-learn multiclass classification model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a scikit-learn multiclass classification model in SAS Model Manager. This beginner-level example uses the scikit-learn library. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained scikit-learn multiclass classification model # model = ... # Instantiate SasModelManager sas_manager = SasModelManager() # Register the model # sas_manager.register_model(model, 'multiclass_classification_model', 'scikit-learn') print("Example for registering scikit-learn multiclass classification model.") ``` -------------------------------- ### Automated Modeling with Python & SAS AutoML Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Performs automated modeling using the SWAT package and registers the results along with a custom XGBoost model to SAS Model Manager using sasctl. ```Python # Example using SWAT for automated modeling and sasctl for registration # import swat # import sasctl # from sasctl.utils import register_model # Connect to SAS Viya # conn = swat.CAS('your_cas_host', 5555, 'username', 'password') # Perform automated modeling (example) # auto_model_results = conn.automl.buildModel(table='your_cas_table', target='your_target_variable') # Register the AutoML model or a custom XGBoost model # register_model(auto_model_results, 'path/to/automl_model.json', 'AutoMLModel', 'SAS AutoML') ``` -------------------------------- ### Get Deployed Module Steps Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/data_science_pilot.ipynb Retrieves the steps associated with a deployed micro-analytic module. It requires the deployed module name and an authorization token. ```Python headers = {'Authorization': 'Bearer ' + token} url = host + '/microanalyticScore/modules/' + deployed_name + '/steps' r = request('GET', url, params={}, headers = headers, verify=False) r.json() ``` -------------------------------- ### Register scikit-learn Regression Model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a regression model created with scikit-learn into SAS Model Manager. ```Python import sasctl from sasctl.utils import register_model # Assuming model_object is a trained scikit-learn regression model # and model_file_path points to the saved model (e.g., pickle file) # register_model(model_object, model_file_path, 'Scikit-Regression', 'scikit-learn') ``` -------------------------------- ### Pickle and Package MLFlow Model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Uses pzmm.PickleModel to pickle the trained MLFlow model and package it into a zip folder, along with MLFlow details, for import into SAS Model Manager. ```Python modelPrefix = 'MLFlowTest' zipFolder = Path.cwd() / 'data/MLFlowModels/Test1/' pzmm.PickleModel.pickle_trained_model(_, modelPrefix, zipFolder, mlflow_details=varDict) ``` -------------------------------- ### Establish SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Establishes a connection to the SAS server using the Session class from sasctl, requiring username, password, and host details for authentication and communication. ```Python import getpass username = getpass.getpass() password = getpass.getpass() host = 'demo.sas.com' sess = Session(host, username, password, protocol='http') ``` -------------------------------- ### Register scikit-learn Classification Model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a classification model created with scikit-learn into SAS Model Manager. ```Python import sasctl from sasctl.utils import register_model # Assuming model_object is a trained scikit-learn classification model # and model_file_path points to the saved model (e.g., pickle file) # register_model(model_object, model_file_path, 'Scikit-Classification', 'scikit-learn') ``` -------------------------------- ### Import SASCTL Python Packages Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Imports necessary modules from the sasctl library, including pathlib for path manipulation and pzmm for SAS Model Manager integration functionalities. ```Python # Pathing support from pathlib import Path # sasctl interface for importing models import sasctl.pzmm as pzmm from sasctl import Session ``` -------------------------------- ### Display Data Head Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_generate_complete_model_card.ipynb Shows the first few rows of the dataset to get a quick overview of the data structure and content. This is a common first step in data exploration. ```Python adult.head() ``` -------------------------------- ### Prepare Data Columns for MLFlow Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Cleans and standardizes data column names using pandas to ensure they are valid Python variable names, preventing issues during MLFlow model logging. ```Python import pandas as pd data = pd.read_csv('data.csv') data.columns = data.columns.str.replace('\W|^(?=\d)', '_', regex=True) ``` -------------------------------- ### Write Model Properties and Metadata JSON Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Creates JSON files for model properties (name, description, target variables) and metadata using pzmm.JSONFiles.writeModelPropertiesJSON and write_file_metadata_json, providing comprehensive information for SAS Model Manager. ```Python # Write model properties to a json file J.writeModelPropertiesJSON(modelName=modelPrefix, modelDesc='MLFlow Model ', targetVariable='', modelType='', modelPredictors='', targetEvent=1, numTargetCategories=1, eventProbVar='tensor', jPath=zipFolder, modeler='sasdemo') # Write model metadata to a json file J.writeFileMetadataJSON(modelPrefix, jPath=zipFolder) ``` -------------------------------- ### Initialize Local Git Repository Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_git_integration_example.ipynb Initializes a new local Git repository. This is a fundamental step before any Git operations can be performed. ```bash git init ``` -------------------------------- ### Install sasctl with Conda Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Installs the sasctl package using the Conda package manager from the sas-institute channel. ```Shell conda install -c sas-institute sasctl ``` -------------------------------- ### Initialize Git Integration Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_git_integration_example.ipynb Initializes the Git integration functionality within the python-sasctl library by creating an instance of GitIntegrate. ```python GI = pzmm.GitIntegrate() ``` -------------------------------- ### Pickling and Packaging the Model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_complete_model_example_MLFlow_sklearn.ipynb Creates a directory for SASCTL assets and pickles the trained MLflow model using `pzmm.PickleModel.pickle_trained_model`. This packages the model and its details for import into SAS Model Manager. ```Python modelPrefix = 'MLFlowDemo' zipFolder = Path.cwd() / f'data/MLFlowModels/{modelPrefix}' pzmm.PickleModel.pickle_trained_model(model_prefix=modelPrefix, pickle_path=zipFolder, mlflow_details=varDict) ``` -------------------------------- ### Register MLFlow model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers an MLFlow model in SAS Model Manager. This intermediate example requires MLflow and is suitable for classification models. ```Python import sasctl from sasctl.pzmm import SasModelManager # Assuming you have a trained MLFlow model # mlflow_model_path = 'path/to/your/mlflow/model' # Instantiate SasModelManager sas_manager = SasModelManager() # Register the MLFlow model # sas_manager.register_model(mlflow_model_path, 'mlflow_classification_model', 'mlflow') print("Example for registering an MLFlow model.") ``` -------------------------------- ### Get Folders via REST API Source: https://github.com/sassoftware/python-sasctl/blob/master/README.md Retrieves folder information from SAS Viya by making a direct GET request to the /folders endpoint. This is a lower-level interaction. ```Python from pprint import pprint from sasctl import Session, get with Session(host, username, password): folders = get('/folders') pprint(folders) ``` -------------------------------- ### sasctl Command Line Help Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Shows how to access the help information for the sasctl command-line utility. This includes available services and general options. ```Shell $ sasctl -h ``` ```Shell $ sasctl folders -h ``` -------------------------------- ### Establish SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_custom_kpi_model_parameters.ipynb Sets up a connection to a SAS server using provided username and password. It requires user input for credentials and specifies the host and protocol for the connection. ```Python username = getpass.getpass() password = getpass.getpass() host = "demo.sas.com" # Changes required by user sess = Session(host, username, password, protocol="http") # For TLS-enabled servers, change protocol value to "https" ``` -------------------------------- ### Register Custom Model Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/README.md Registers a model in SAS Model Manager by explicitly providing all necessary files and model details. ```Python import sasctl from sasctl.utils import register_model # Assuming custom_model_files is a list of file paths for the custom model # and model_details is a dictionary containing model metadata # register_model(model_files=custom_model_files, model_details=model_details, model_type='custom') ``` -------------------------------- ### SASCTL Environment Variables for Testing Source: https://github.com/sassoftware/python-sasctl/blob/master/CONTRIBUTING.md Configuration environment variables required for testing SAS Viya integrations with python-sasctl. These variables specify server details, authentication credentials, and SSL certificate paths. ```Shell export SASCTL_SERVER_NAME="your_sas_viya_hostname" export SASCTL_AUTHINFO="/path/to/.authinfo or .netrc" export SASCTL_USER_NAME="your_sas_viya_username" export SASCTL_PASSWORD="your_sas_viya_password" export REQUESTS_CA_BUNDLE="/path/to/ca_certificate.pem" ``` -------------------------------- ### Establish SAS Viya Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_complete_model_example_MLFlow_sklearn.ipynb This code snippet demonstrates how to create a SAS Viya session using the Session class. It securely prompts the user for their username, password, and hostname. The session is established with an HTTP protocol. ```python import getpass username = getpass.getpass("Username: ") password = getpass.getpass("Password: ") host = getpass.getpass("Hostname: ") sess = Session(host, username, password, protocol='http') ``` -------------------------------- ### List Folders using Python Module Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Demonstrates how to list folders in SAS Viya using the sasctl Python module. This requires an active session to the SAS Viya platform. ```Python >>> from sasctl import Session >>> s = Session(host, username, password) ``` ```Python >>> from sasctl import Session, register_model >>> from sklearn import linear_model as lm >>> with Session('example.com', authinfo=): ... model = lm.LogisticRegression() ... register_model(model, 'Sklearn Model', 'My Project') ``` ```Python >>> from sasctl import Session >>> from sasctl.services import folders >>> with Session(host, username, password): ... for f in folders.list_folders(): ... print(f) ``` ```Python >>> from pprint import pprint >>> from sasctl import get, Session >>> with Session(host, username, password): ... folders = get('/folders') ... pprint(folders) ``` -------------------------------- ### Contributor Sign-off Example Source: https://github.com/sassoftware/python-sasctl/blob/master/ContributorAgreement.txt This snippet demonstrates the required 'Signed-off-by' line format for contributions, which must include the contributor's real name and email address. ```text Signed-off-by: Random J Developer ``` -------------------------------- ### Set Up SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_regression_assess_model_bias.ipynb Establishes a connection to a SAS environment using the `Session` class from the `sasctl` library. It requires hostname, username, and password, with the password input masked for security. ```Python from sasctl import Session import getpass # setting up environment hostname = "" username = input("Username: ") password = getpass.getpass("Password: ") # changes required by user sess = Session(hostname, username, password, protocol="http") ``` -------------------------------- ### Import pzmm Module in Python Source: https://github.com/sassoftware/python-sasctl/blob/master/src/sasctl/pzmm/README.md Demonstrates how to import the pzmm module from the sasctl package in Python. This is the standard way to begin using the module's functionalities after installation. ```Python import sasctl.pzmm as pzmm ``` -------------------------------- ### Establish SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleRegression.ipynb Prompts the user for username and password, then establishes an HTTP session with the SAS demo server using the sasctl.Session class. ```Python import getpass\username = getpass.getpass()\npassword = getpass.getpass()\nhost = 'demo.sas.com'\nsess = Session(host, username, password, protocol='http') ``` -------------------------------- ### Correct Package Names in requirements.json Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_generate_requirements_json.ipynb Iterates through the generated requirements and corrects potential discrepancies in package names, such as changing 'sklearn' to 'scikit-learn' for accurate pip installation. ```Python for requirement in requirements_json: if 'sklearn' in requirement['step']: requirement['command'] = requirement["command"].replace('sklearn', 'scikit-learn') requirement['step'] = requirement['step'].replace('sklearn', 'scikit-learn') print(json.dumps(requirements_json, sort_keys=True, indent=4)) ``` -------------------------------- ### Create SAS Viya Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_git_integration_example.ipynb Establishes a session to SAS Viya by prompting the user for server name, username, and password. It uses HTTP protocol for the connection. ```python server = input('Server Name: ') username = input('Username: ') password = getpass.getpass('Password') sess = Session(server, username, password, protocol='http') ``` -------------------------------- ### Create SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleH2O.ipynb This code snippet demonstrates how to create a SAS session using the Session class. It requires username, password, and host details, and supports specifying the protocol (e.g., 'http'). ```Python import getpass username = getpass.getpass() password = getpass.getpass() host = 'sas.demo.com' sess = Session(host, username, password, protocol='http') ``` -------------------------------- ### Get Model Class Labels Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_classification_assess_model_bias.ipynb Retrieves the class labels that the trained Random Forest Classifier model can predict. This is useful for understanding the target categories. ```Python # Assuming rfc is a trained model rfc.classes_ ``` -------------------------------- ### Connect to SAS Viya Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_generate_complete_model_card.ipynb Establishes a connection to a SAS Viya environment using provided credentials and URL. It utilizes the `sasctl` library for authentication and creates a SWAT connection. ```python # Step 2: Connect to SAS Viya username = input("Username: ") password = getpass.getpass("Password: ") host = input("Viya Environment URL: ") sess = Session(host, username, password, protocol="http") # For TLS-enabled servers, change protocol value to "https" conn = sess.as_swat() # Connect to SWAT through the sasctl authenticated connection ``` -------------------------------- ### Build Tox Documentation Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Builds the project's documentation using the specified Python interpreter environment. ```Shell $ tox -e pyXX-doc ``` -------------------------------- ### Configure Global Package Options Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/score_testing_example.ipynb Sets global options for pandas to disable chained assignment warnings and configures matplotlib's font size for better readability. It also includes a warning filter for pandas related to SWAT deprecation. ```Python # Global Package Options pd.options.mode.chained_assignment = None # default="warn" plt.rc("font", size=14) # Ignore warnings from pandas about SWAT using a feature that will be depreciated soon warnings.simplefilter(action="ignore", category=FutureWarning) ``` -------------------------------- ### Infer MLFlow Model Signature Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Imports the infer_signature function from MLFlow to capture model input and output schemas, which is crucial for SAS Model Manager integration. ```Python from mlflow.models.signature import infer_signature ``` -------------------------------- ### Get SAS Access Token Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/data_science_pilot.ipynb Obtains an access token from the SAS Logon service using username and password authentication. This token is required for subsequent API requests. ```Python host = 'http://' + hostname url = host + '/SASLogon/oauth/token' r = request('POST', url, data='grant_type=password&username=%s&password=%s' %(username, password), headers={ 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, auth=('sas.ec', ''), verify=False) token = r.json()['access_token'] ``` -------------------------------- ### SASCTL: Get Link Metadata Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Retrieves metadata for a specific HATEOAS link associated with a SAS object. This function simplifies accessing linked resources without manual parsing. ```Python sasctl.core.get_link(object, 'rel') ``` -------------------------------- ### Pickle Trained Models with pzmm Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExample.ipynb This snippet demonstrates how to pickle trained machine learning models using the pzmm.PickleModel.pickle_trained_model function. It iterates through a list of models, prefixes, and corresponding directories, pickling each model into its designated folder. ```Python modelPrefix = ['DecisionTreeClassifier', 'RandomForest', 'GradientBoosting'] zipFolder = [Path.cwd() / 'data/hmeqModels/DecisionTreeClassifier/', Path.cwd() / 'data/hmeqModels/RandomForest/', Path.cwd() / 'data/hmeqModels/GradientBoosting'] # User created directories model = [treeModel, forestModel, gradientModel] for (m, prefix, path) in zip(model, modelPrefix, zipFolder): pzmm.PickleModel.pickle_trained_model(m, prefix, path) ``` -------------------------------- ### Configure Plotting Parameters Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_regression_assess_model_bias.ipynb Sets the figure size and layout for matplotlib plots to ensure optimal display of visualizations. This is a common setup step before generating plots. ```Python plt.rcParams["figure.figsize"] = [12, 4] plt.rcParams["figure.autolayout"] = True ``` -------------------------------- ### Get Decision Tree Classes Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_classification_assess_model_bias.ipynb This code snippet retrieves the class labels or attributes associated with a decision tree model object, likely stored in the 'dtc' variable. ```Python dtc.classes_ ``` -------------------------------- ### Register scikit-learn Model using Python Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Demonstrates registering a scikit-learn model with SAS Viya using sasctl. This involves fitting the model and then registering it via a sasctl session. ```Python from sklearn.linear_model import LogisticRegression from sasctl import register_model, Session model = LogisticRegression() model.fit(X, y) # Establish a session with Viya with Session('hostname', 'username', 'password'): register_model(model, 'Model Name', 'Project Name', input=X) ``` -------------------------------- ### Collect MLFlow Model Details Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Reads MLFlow model files from a specified path using pzmm.MLFlowModel.read_mlflow_model_file to extract variable, input, and output dictionaries required for SAS registration. ```Python mlPath = Path('C:/Users/sclind/Documents/Python Scripts/MLFlow/mlruns/0/7100d4e854224371b39c4a9589317121/artifacts/model') varDict, inputsDict, outputsDict = pzmm.MLFlowModel.read_mlflow_model_file(_, mlPath) ``` -------------------------------- ### Configure Plotting Defaults in Python Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_classification_assess_model_bias.ipynb Sets the default figure size and enables automatic layout for plots using matplotlib. This is a common setup step for generating visualizations. ```Python plt.rcParams["figure.figsize"] = [7, 4] plt.rcParams["figure.autolayout"] = True ``` -------------------------------- ### Specify Local Git Repository Path Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_git_integration_example.ipynb Prompts the user to input the path to their local Git repository and stores it as a Path object for further use. ```python path = input('Local Git Repo Path: ') gPath = Path(path) ``` -------------------------------- ### Register SAS Model using Python Source: https://github.com/sassoftware/python-sasctl/blob/master/doc/index.rst Example of registering a SAS model (stored in a CAS table) with SAS Viya using the sasctl library. Requires a CAS session and a sasctl session. ```Python import swat from sasctl import register_model, Session with swat.CAS('hostname', 5570, 'username', 'password') as cas: astore = cas.CASTable('model_astore_table') Session('hostname', 'username', 'password'): model = register_model(astore, 'Model Name', 'Project Name') ``` -------------------------------- ### Log MLFlow Model with Signature Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/ARCHIVE/v1_8/pzmmModelImportExampleMLFlow.ipynb Logs an MLFlow model using mlflow.sklearn.log_model, including the inferred signature and the model's prediction function, preparing it for SAS Model Manager import. ```Python import mlflow signature = infer_signature(data, model.predict(data)) mlflow.sklearn.log_model(model, "model", signature=signature) ``` -------------------------------- ### Load Data Science Pilot Action Set Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/data_science_pilot.ipynb Loads the 'dataSciencePilot' action set into the CAS connection, enabling access to its functionalities. ```Python conn.builtins.loadactionset('dataSciencePilot') ``` -------------------------------- ### Initialize H2O Cluster Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_h2o_model_import.ipynb Initializes the H2O cluster, which is required before performing any H2O operations. This function connects to or starts an H2O cluster, making it ready for model training. ```Python h2o.init() ``` -------------------------------- ### Python Package Imports for SASCTL Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_custom_kpi_model_parameters.ipynb Imports necessary libraries from the standard library, third-party packages (like pandas and pickle), and the sasctl application for interacting with SAS Model Manager. ```Python # Standard Library from pathlib import Path import warnings import getpass # Third Party import pandas as pd import pickle # Application Specific from sasctl import Session from sasctl.pzmm.model_parameters import ModelParameters as mp # Global Package Options pd.options.mode.chained_assignment = None # default="warn" warnings.simplefilter(action="ignore", category=FutureWarning) ``` -------------------------------- ### Establish SAS Session Source: https://github.com/sassoftware/python-sasctl/blob/master/examples/pzmm_regression_model_import.ipynb This snippet shows how to establish a connection to a SAS server using the `Session` class. It requires the host address, username, and password. The protocol can be set to 'http' or 'https' depending on the server's configuration. ```Python import getpass from sasctl import Session username = getpass.getpass() password = getpass.getpass() host = "demo.sas.com" # Changes required by user sess = Session(host, username, password, protocol="http") # For TLS-enabled servers, change protocol value to "https" ```