domino logo
Tech Ecosystem
Get started with Python
Step 0: Orient yourself to DominoStep 1: Create a projectStep 2: Configure your projectStep 3: Start a workspaceStep 4: Get your files and dataStep 5: Develop your modelStep 6: Clean up WorkspacesStep 7: Deploy your model
Get started with R
Step 0: Orient yourself to Domino (R Tutorial)Step 1: Create a projectStep 2: Configure your projectStep 3: Start a workspaceStep 4: Get your files and dataStep 5: Develop your modelStep 6: Clean up WorkspacesStep 7: Deploy your model
Get Started with MATLAB
Step 1: Orient yourself to DominoStep 2: Create a Domino ProjectStep 3: Configure Your Domino ProjectStep 4: Start a MATLAB WorkspaceStep 5: Fetch and Save Your DataStep 6: Develop Your ModelStep 7: Clean Up Your Workspace
Step 8: Deploy Your Model
Scheduled JobsLaunchers
Step 9: Working with Domino Datasets
Domino Reference
Notifications
On-Demand Open MPI
Configure MPI PrerequisitesFile Sync MPI ClustersValidate MPI VersionWork with your ClusterManage Dependencies
Projects
Projects Overview
Revert Projects and Files
Revert a ProjectRevert a File
Projects PortfolioReference ProjectsProject Goals in Domino 4+
Git Integration
Git Repositories in DominoGit-based Projects with CodeSyncWorking from a Commit ID in Git
Jira Integration in DominoUpload Files to Domino using your BrowserFork and Merge ProjectsSearchSharing and CollaborationCommentsDomino Service FilesystemCompare File RevisionsArchive a Project
Advanced Project Settings
Project DependenciesProject TagsRename a ProjectSet up your Project to Ignore FilesUpload files larger than 550MBExporting Files as a Python or R PackageTransfer Project Ownership
Domino Runs
JobsDiagnostic Statistics with dominostats.jsonNotificationsResultsRun Comparison
Advanced Options for Domino Runs
Run StatesDomino Environment VariablesEnvironment Variables for Secure Credential StorageUse Apache Airflow with Domino
Scheduled Jobs
Domino Workspaces
WorkspacesUse Git in Your WorkspaceRecreate A Workspace From A Previous CommitUse Visual Studio Code in Domino WorkspacesPersist RStudio PreferencesAccess Multiple Hosted Applications in one Workspace Session
Spark on Domino
On-Demand Spark
On-Demand Spark OverviewValidated Spark VersionConfigure PrerequisitesWork with your ClusterManage DependenciesWork with Data
External Hadoop and Spark
Hadoop and Spark OverviewConnect to a Cloudera CDH5 cluster from DominoConnect to a Hortonworks cluster from DominoConnect to a MapR cluster from DominoConnect to an Amazon EMR cluster from DominoRun Local Spark on a Domino ExecutorUse PySpark in Jupyter WorkspacesKerberos Authentication
On-Demand Ray
On-Demand Ray OverviewValidated Ray VersionConfigure PrerequisitesWork with your ClusterManage DependenciesWork with Data
On-Demand Dask
On-Demand Dask OverviewValidated Dask VersionConfigure PrerequisitesWork with Your ClusterManage DependenciesWork with Data
Customize the Domino Software Environment
Environment ManagementDomino Standard EnvironmentsInstall Packages and DependenciesAdd Workspace IDEsAdding Jupyter Kernels
Use Custom Images as a Compute Environment
Pre-requisites for Automatic Custom Image CompatibilityModify the Default Workspace ToolsCreate a Domino Image with an NGC ContainerCreate a Domino Environment with a Pre-Built ImageManually Modify Images for Domino Compatibility
Partner Environments for Domino
Use MATLAB as a WorkspaceUse Stata as a WorkspaceUse SAS as a Workspace
Advanced Options for Domino Software Environment
Publish in Domino with Custom ImagesInstall Custom Packages in Domino with Git IntegrationAdd Custom DNS Servers to Your Domino EnvironmentConfigure a Compute Environment to User Private Cran/Conda/PyPi MirrorsUse TensorBoard in Jupyter Workspaces
Publish your Work
Publish a Model API
Model Publishing OverviewModel Invocation SettingsModel Access and CollaborationModel Deployment ConfigurationPromote Projects to ProductionExport Model ImageExport to NVIDIA Fleet Command
Publish a Web Application
App Publishing OverviewGet Started with DashGet Started with ShinyGet Started with FlaskContent Security Policies for Web Apps
Advanced Web Application Settings in Domino
App Scaling and PerformanceHost HTML Pages from DominoHow to Get the Domino Username of an App Viewer
Launchers
Launchers OverviewAdvanced Launcher Editor
Assets Portfolio Overview
Model Monitoring and Remediation
Monitor WorkflowsData Drift and Quality Monitoring
Set up Monitoring for Model APIs
Set up Prediction CaptureSet up Drift DetectionSet up Model Quality MonitoringSet up NotificationsSet Scheduled ChecksSet up Cohort Analysis
Set up Model Monitor
Connect a Data SourceRegister a ModelSet up Drift DetectionSet up Model Quality MonitoringSet up Cohort AnalysisSet up NotificationsSet Scheduled ChecksUnregister a Model
Use Monitoring
Access the Monitor DashboardAnalyze Data DriftAnalyze Model QualityExclude Features from Scheduled Checks
Remediation
Cohort Analysis
Review the Cohort Analysis
Remediate a Model API
Monitor Settings
API TokenHealth DashboardNotification ChannelsTest Defaults
Monitoring Config JSON
Supported Binning Methods
Model Monitoring APIsTroubleshoot the Model Monitor
Connect to your Data
Data in Domino
Datasets OverviewProject FilesDatasets Best Practices
Connect to Data Sources
External Data VolumesDomino Data Sources
Connect to External Data
Connect Domino to DataRobotConnect to Amazon S3 from DominoConnect to Azure Data Lake StorageConnect to BigQuery from DominoConnect to Generic S3 from DominoConnect to Google Cloud StorageConnect to IBM DB2 from DominoConnect to IBM Netezza from DominoConnect to Impala from DominoConnect to MSSQL from DominoConnect to MySQL from DominoConnect to Okera from DominoConnect to Oracle Database from DominoConnect to PostgreSQL from DominoConnect to Redshift from DominoConnect to Snowflake from DominoConnect to Teradata from Domino
Work with Data Best Practices
Work with Big Data in DominoWork with Lots of FilesMove Data Over a Network
Advanced User Configuration Settings
User API KeysDomino TokenOrganizations Overview
Use the Domino Command Line Interface (CLI)
Install the Domino Command Line (CLI)Domino CLI ReferenceDownload Files with the CLIForce-Restore a Local ProjectMove a Project Between Domino DeploymentsUse the Domino CLI Behind a Proxy
Browser Support
Get Help with Domino
Additional ResourcesGet Domino VersionContact Domino Technical SupportSupport Bundles
domino logo
About Domino
Domino Data LabKnowledge BaseData Science BlogTraining
User Guide
>
Get started with Python
>
Step 5: Develop your model

Step 5: Develop your model

When you are developing your model, you want to be able to quickly execute code, see outputs, and make iterative improvements. Domino enables this with Workspaces. Step 3 covered starting a Workspace and explored Workspace options like VSCode, RStudio, and Jupyter.

In this section, we will use Jupyter to load, explore, and transform some data. After the data has been prepared, we will train a model.

Step 5.1: Load and explore the dataset

  1. From the project menu, click Workspaces.

  2. Click Open Last Workspace or Open in the workspace created in Step 3. In /mnt, you can see data.csv. If not, go to Step 4 to download the dataset.

    jupyter_logo_in_workspace

  3. Use the New menu to create a Python notebook.

    new python3 notebook

  4. Starting in the first cell, enter these lines to import some packages. After each line, press Shift+Enter to execute:

    %matplotlib inline
    import pandas as pd
    import datetime
  5. Next, read the file you downloaded into a pandas dataframe:

    df = pd.read_csv('data.csv', skiprows=1, skipfooter=1, header=None, engine='python')
  6. Rename the columns according to information on the column headers at https://www.bmreports.com/bmrs/?q=generation/fueltype/current and display the first five rows of the dataset using df.head().

    df.columns = ['HDF', 'date', 'half_hour_increment',
                  'CCGT', 'OIL', 'COAL', 'NUCLEAR',
                  'WIND', 'PS', 'NPSHYD', 'OCGT',
                  'OTHER', 'INTFR', 'INTIRL', 'INTNED',
                   'INTEW', 'BIOMASS', 'INTEM','INTEL',
                   'INTIFA2', 'INTNSL']
    df.head()

    jupyter_first_df

    We can see that this is a time series dataset. Each row is a successive half hour increment during the day that details the amount of energy generated by fuel type. Time is specified by the date and half_hour_increment columns.

  7. Create a new column named datetime that represents the starting datetime of the measured increment. For example, a 20190930 date and 2 half hour increment means that the time period specified is September 19, 2019 from 12:30am to 12:59am.

    df['datetime'] = pd.to_datetime(df['date'], format="%Y%m%d")
    df['datetime'] = df.apply(lambda x:x['datetime']+ datetime.timedelta(minutes=30*(int(x['half_hour_increment'])-1)), axis = 1)
  8. Visualize the data to see how each fuel type is used during the day by plotting the data.

    df.drop(
        ['HDF', 'date', 'half_hour_increment'], axis = 1
        ).set_index('datetime').plot(figsize=(15,8))

    fuel types graph cell

    The CCGT column, representing combined-cycle gas turbines, generates a lot of energy and is volatile.

    We will concentrate on this column and try to predict the power generation from this fuel source.

Step 5.2: Train a model

Data scientists have access to many libraries and packages that help with model development. Some of the most common for Python are XGBoost, Keras and scikit-learn. These packages are already installed in the Domino Standard Environment, . However, there might be times when you want to experiment with a package that is not installed in the environment.

We will build a model with the Facebook Prophet package, which is not installed into the default environment. You will see that you can quickly get started with new packages and algorithms just as fast as they are released into the open source community.

  1. In the next Jupyter cell, install Facebook Prophet and its dependencies, including PyStan (a slightly older version of Plotly). PyStan requires 4 GB of RAM to be installed. Make sure your workspace is set to use a large enough hardware tier:

    !pip install -q --user "convertdate==2.1.2" "holidays==0.10.3" "lunarcalendar==0.0.9" "pystan==2.19.1.1"
    !pip install -q --user "fbprophet==0.7.1"
  2. For Facebook Prophet, the time series data needs to be in a DataFrame with 2 columns named ds and y:

    df_for_prophet = df[['datetime', 'CCGT']].rename(columns = {'datetime':'ds', 'CCGT':'y'})
  3. Split the dataset into train and test sets:

    X = df_for_prophet.copy()
    y = df_for_prophet['y']
    proportion_in_training = 0.8
    split_index = int(proportion_in_training*len(y))
    X_train, y_train = X.iloc[:split_index], y.iloc[:split_index]
    X_test, y_test = X.iloc[split_index:], y.iloc[split_index:]
  4. Import Facebook Prophet and fit a model:

    from fbprophet import Prophet
    m = Prophet()
    m.fit(X_train)

    If you encounter an error when running this cell, you may need to downgrade your pandas version first. In that case you would run

    !pip install -Iq --user "pandas==1.3.4"

    and then

    from fbprophet import Prophet
    m = Prophet()
    m.fit(X_train)

    After running the code above, you may encounter a warning about code deprecation. The warning can be ignored for the purposes of this walkthrough.

  5. Make a DataFrame to hold prediction and predict future values of CCGT power generation:

    future = m.make_future_dataframe(periods=int(len(y_test)/2), freq='H')
    forecast = m.predict(future)
    # forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() #uncomment to inspect the DataFrame
  6. Plot the fitted line with the training and test data:

    import matplotlib.pyplot as plt
    plt.gcf()
    fig = m.plot(forecast)
    plt.plot(X_test['ds'].dt.to_pydatetime(), X_test['y'], 'r', linewidth = 1, linestyle = '--', label = 'real')
    plt.legend()
  7. Rename the notebook to be Forecast_Power_Generation

    rename_notebook-1

    rename_notebook-2

  8. Save the notebook.

    save_notebook

Step 5.3: Export the model

Trained models are meant to be used. There is no reason to re-train the model each time you use the model. Export or serialize the model to a file to load and reuse the model later. In Python, the pickle module implements protocols for serializing and de-serializing objects. In R, you can commonly use the serialize command to create RDS files.

  1. Export the trained model as a pickle file for later use:

    import pickle
    # m.stan_backend.logger = None    #uncomment if using Python 3.6 and fbprophet==0.6
    with open("model.pkl", "wb") as f:
          pickle.dump(m, f)

We will use the serialized model in Step 7 when we create an API from the model.

Domino Data LabKnowledge BaseData Science BlogTraining
Copyright © 2022 Domino Data Lab. All rights reserved.