Step 5: Develop your model




Introduction

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. If you have not done so, please complete Step 4 to download the dataset.

  2. Click the Jupyter logo at the top to return to the files browser within thhe Jupyter Workspace. You should see data.csv in /mnt. If not, please return 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. In the first cell, enter these lines to import some packages, then hit Shift+Enter to execute:

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

    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.

    df.columns = ['HDF', 'date', 'half_hour_increment',
                  'CCGT', 'OIL', 'COAL', 'NUCLEAR',
                  'WIND', 'PS', 'NPSHYD', 'OCGT',
                  'OTHER', 'INTFR', 'INTIRL', 'INTNED',
                   'INTEW', 'BIOMASS', 'INTEM']
    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.

  1. 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['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)
    
  1. 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” 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 Python are XGBoost, Keras, and scikit-learn. These packages are already installed in the Domino Analytics Distribution, 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 the next Jupyter cell, install Facebook Prophet, which also requires PyStan and a slightly older version of Plotly to be compatible with Prophet:

    !sudo -H pip install -q --disable-pip-version-check "pystan==2.17.1.0" "plotly<4.0.0"
    !pip install -q --disable-pip-version-check fbprophet
    
  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)
    
  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
    
    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.