domino logo
Tech Ecosystem
Get Started
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 ProjectStep 3: Configure Your 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 Datasets
Domino Reference Projects
Search in Deployments
Security and Credentials
Secure Credential Storage
Store Project CredentialsStore User CredentialsStore Model Credentials
Get API KeyUse a Token for AuthenticationCreate a Mirror of Compute Environments
Collaborate
Share and Collaborate on Projects
Set Project VisibilityInvite CollaboratorsCollaborator Permissions
Add Comments
Reuse Work
Set Up ExportsSet Up Imports
Organizations
Organization PermissionsTransfer Projects to an Organization
Projects
Domino File System Projects
Domino File SystemOrganize Domino File System Project AssetsImport Git RepositoriesWork from a Commit ID in GitCopy a ProjectFork ProjectsMerge Projects
Manage Project Files
Upload Files to DominoCompare File RevisionsExclude Project Files From SyncExport Files as Python or R Package
Archive a Project
Revert Projects and Files
Revert a FileRevert a Project
Git-based Projects
Git-based Project Directory StructureCreate a Git-based ProjectCreate a New RepositoryOrganize Git-based Project AssetsDevelop Models in a WorkspaceSave Artifacts to the Domino File System
Project FilesSet Project SettingsStore Project Credentials
Project Goals
Add GoalsEdit GoalsLink Work to Goals
Organize Projects with TagsSet Project Stages
Project Status
Set Project as BlockedSet Project as CompleteSet Project as Unblocked
View Execution DetailsView Project ActivityTrack Project StatusRename a Project
Share and Collaborate
Set Project VisibilityInvite CollaboratorsCollaborator Permissions
Export and Import Project Content
Set Up ExportsSet Up Imports
See the Assets for Your ProjectPromote Projects to ProductionTransfer Project OwnershipIntegrate Jira
Domino Datasets
Manage Large DataDatasets Best PracticesCreate a DatasetUse an Existing DatasetFile Location of Datasets in Projects
Datasets and Snapshots
Update a DatasetAdd Tags to SnapshotsCreate a Snapshot of a DatasetDelete Snapshots of DatasetsDelete a Dataset
Upgrade from Versions Prior to 4.5
External Data
Considerations for Connecting to Data Sources
External Data Volumes
Mount an External VolumeView Mounted VolumesUse a Mounted VolumeUmount a Volume
Tips: Transfer Data Over a Network
Workspaces
Create a Workspace
Open a VS Code WorkspaceSet Custom Preferences for RStudio Workspaces
Workspace Settings
Edit Workspace SettingsChange Your Workspace's Volume SizeConfigure Long-Running Workspaces
Save Work in a WorkspaceSync ChangesView WorkspacesStop a WorkspaceResume a WorkspaceDelete a WorkspaceView Workspace LogsView Workspace UsageView Workspace HistoryWork with Legacy Workspaces
Use Git in Your Workspace
Commit and Push Changes to Your Git RepositoryCommit All Changes to Your Git RepositoryPull the Latest Changes from Your Git Repository
Run Multiple Applications in a Workspace
Clusters
Spark on Domino
Hadoop and Spark Overview
Connect 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 Spark Overview
Validated Spark VersionConfigure PrerequisitesWork with your ClusterManage DependenciesWork with Data
On-Demand Ray Overview
Validated Ray VersionConfigure PrerequisitesWork with your ClusterManage DependenciesWork with Data
On-Demand Dask Overview
Validated Dask VersionConfigure PrerequisitesWork with Your ClusterManage DependenciesWork with Data
Environments
Set a Default EnvironmentCreate an EnvironmentEdit Environment DefinitionView Your EnvironmentsView Environment RevisionsDuplicate an EnvironmentArchive an Environment
Environments
Example: Create a New Environment
Customize Environments
Install Custom Packages with Git Integration
Add Packages to Environments
Use Dockerfile InstructionsUse requirements.txt (Python only)Use the Execution to Add a Package
Add Workspace IDEsAdd a Scala KernelAccess Additional Domains and HostnamesUse TensorBoard in Jupyter Workspaces
Use Partner Environments
Use MATLAB as a WorkspaceUse Stata as a WorkspaceAdd an NVIDIA NGC to DominoUse SAS as a Workspace
Executions
Execution StatesDomino Environment Variables
Jobs
Start a JobScheduled Jobs
Launchers
Launchers OverviewCreate a LauncherRun a LauncherCopy Launcher Definitions
View Job DetailsCompare JobsTag JobsStop JobsView Execution Performance
Execution Notifications
Set Notification PreferencesSet Custom Execution Notifications
Execution Results
Download Execution ResultsCustomize the Results DashboardAutomate Complex Pipelines with Apache Airflow
Model APIs
Configure a Model for Deployment
Scale Models
Scale Python ModelsScale Model Versions
Configure Compute ResourcesRoute Your ModelProject Files in ModelsEnvironments for ModelsShare and Collaborate on Models
Publish
Model APIs
Publish a ModelSend Test Calls to the ModelPublish a New Version of a ModelSelect How to Authorize a Model
Domino Apps
Publish a Domino AppHost HTML Pages from DominoGrant Access to Domino AppsView a Domino AppView All Domino AppsIdentify Resources to WhitelistPublish a Python App with DashPublish an R App with ShinyPublish a Project as a Website with FlaskOptimize App Scalability and PerformanceGet the Domino Username of an App Viewer
Launchers
Create a LauncherRun a LauncherCopy Launcher Definitions
Model Monitoring
Model Monitoring APIsAccessing The Model MonitorGet Started with Model MonitoringModel Monitor DeploymentIngest Data into The Model MonitorModel RegistrationMonitoring Data DriftMonitoring Model QualitySetting Scheduled Checks for the ModelConfigure Notification Channels for the ModelUse Model Monitoring APIsProduct Settings
Domino Command Line Interface (CLI)
Install the Domino Command Line Interface (CLI)Domino CLI ReferenceDownload Files with the CLIForce-Restore a Local ProjectMove a Project Between DeploymentsUse the Domino CLI Behind a Proxy
Troubleshooting
Troubleshoot Domino ModelsWork with Many FilesTroubleshoot Imports
Get Help
Additional ResourcesGet Domino VersionContact Technical SupportSupport BundlesBrowser SupportUser Guide Updates
domino logo
About Domino
Domino Data LabKnowledge BaseData Science BlogTraining
User Guide
>
Get Started
>
Get started with R
>
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 Rstudio 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. If you have not done so, complete Step 4 to download the dataset. You should see data.csv in /mnt in files pane. If not, return to Step 4 to download the dataset.

    rstudio_files

  2. Use the New menu to create a R script and save is as power.R.

    rstudio_first_df

  3. Enter these lines to import some packages:

    library(tidyverse)
    library(lubridate)
  4. Create a list of the columns according to information on the column headers at Generation by Fuel Type.

    col_names <-  c('HDF', 'date', 'half_hour_increment',
         'CCGT', 'OIL', 'COAL', 'NUCLEAR',
         'WIND', 'PS', 'NPSHYD', 'OCGT',
         'OTHER', 'INTFR', 'INTIRL', 'INTNED',
         'INTEW', 'BIOMASS', 'INTEM')
  5. Read the file you downloaded into a dataframe and set the column names, then display the data:

    #Load the data into a data frame
    df <- read.csv('data.csv',header = FALSE,col.names = col_names,stringsAsFactors = FALSE)
    
    #remove the first and last row
    df <- df[-1,]
    df <- df[-nrow(df),]
    
    #Preview the data
    View(df)
  6. Execute the script by selecting Code > Source. This opens the content of the df data frame in a new tab:

    rstudio 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. Tidy that data so that variables are in columns, observations are in rows, and values are in cells. Switch back to the power.R code tab and add the following:

    df_tidy <- df %>% gather('CCGT', 'OIL', 'COAL', 'NUCLEAR',
                    'WIND', 'PS', 'NPSHYD', 'OCGT',
                    'OTHER', 'INTFR', 'INTIRL', 'INTNED',
                    'INTEW', 'BIOMASS', 'INTEM', key="fuel", value="megawatt" )
  8. Create a new column 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_tidy <- df_tidy %>% mutate(datetime=as.POSIXct(as.Date(date, "%Y%m%d"))+minutes(30*(half_hour_increment-1)))
  9. Visualize the data to see how each fuel type is used during the day by plotting the data.

    #plot the graph
    p <- ggplot(data=df_tidy, aes(x=datetime, y=megawatt, group=fuel)) +
      geom_line(aes(color=fuel))
    print(p)

    Execute the script again by selecting Code > Source. This will update the Plot tab:

    fuel types graph cell r

    The CCGT column representing "combined-cycle gas turbines" seems to be the most interesting. It generates a lot of energy and is very 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 R are randomForest, caret, and nnet. These packages are already installed in the Domino Standard Environment, the default environment. However, there may be times that you want to experiment with a package that is new and 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 your R console, install Facebook Prophet. This might take >5 minutes to install. If it fails, make sure that you’ve selected a hardware tier with >2gb of ram:

    # Install specific version of the prerequisite RcppParallel package as its latest version 5.0.2 fails to install
    install.packages('https://cran.r-project.org/src/contrib/Archive/RcppParallel/RcppParallel_5.0.1.tar.gz', repos=NULL, type="source")
    # Now install latest version of Facebook Prophet
    install.packages('prophet')
  2. For Facebook Prophet, the time series data needs to be in a DataFrame with 2 columns named ds and y. Let’s rename the columns and filter to just to fuel type "CCGT":

    df_CCGT <- df_tidy %>% filter(fuel=="CCGT") %>% select(datetime,megawatt)
    
    names(df_CCGT) <- c("ds","y")
  3. Split the dataset into train and test sets:

    split_index <- round(nrow(df_CCGT)*.8)
    df_CCGT_train <- df_CCGT[1:split_index,]
    df_CCGT_test <- df_CCGT[(split_index+1):nrow(df_CCGT),]
  4. Import Facebook Prophet and fit a model:

    library(prophet)
    m <- prophet(df_CCGT_train)
  5. Make a DataFrame to hold prediction and predict future values of CCGT power generation:

    predict_ln <- round(nrow(df_CCGT_test)/2)
    future <- make_future_dataframe(m, periods = predict_ln,freq = 1800 )
    forecast <- predict(m, future)
  6. Plot the fitted line with the training and test data:

    p <- dyplot.prophet(m, forecast)
    print(p)
  7. Save the code.

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 R, you can commonly use the saveRDS command to create RDS files.

  1. Export the trained model as an rds file for later use:

    saveRDS(m, file = "model.rds")

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.