In a previous example, we saw how we can use the MLPClassifier to classify data using a neural network. However, what if we wish to use a neural network to solve a regression problem; i.e. one where the dependent variable is an interval one? This is where the Keras library comes in.
For this purpose, we will use a linear activation function within the Keras library to create a regression-based neural network. Specifically, we will use an electricity dataset for a list of houses to determine electricity usage. You can access the full code and dataset here at my Github repository.
Our variables are as follows:
- kwatt: Electricity usage by a household per month in kilowatts
- celsius: Average daily temperature at time of measurement
- housesize_sqft: House size in square feet
- water_m3: Monthly water consumption in cubic meters
- sunhours: Hours of sunlight
Firstly, we import our libraries. Note that you will need TensorFlow installed on your system to be able to execute the below code. Depending on your operating system, you can find one of my YouTube tutorials on how to install on Windows 10 here.
Libraries
from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Dense from tensorflow.python.keras.wrappers.scikit_learn import KerasRegressor import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler
Set Directory
import os; path="C:/Users/michaeljgrogan/Documents/a_documents/computing/data science/datasets" os.chdir(path) os.getcwd()
Since we are implementing a neural network, the variables need to be normalized in order for the neural network to interpret them properly. Therefore, our variables are transformed using the MaxMinScaler():
#Variables
dataset=np.loadtxt("electricitydata.csv", delimiter=",")
x=dataset[:,0:4]
y=dataset[:,0]
y=np.reshape(y, (-1,1))
scaler = MinMaxScaler()
print(scaler.fit(x))
print(scaler.fit(y))
xscale=scaler.transform(x)
yscale=scaler.transform(y)
The data is then split into training and test data:
X_train, X_test, y_train, y_test = train_test_split(xscale, yscale)
Keras Model Configuration: Neural Network API
Now, we train the neural network. We are using the four input variables (celsius, housesize_sqft, water_m3, sunhours), along with four hidden neurons, and finally using the linear activation function to process the output.
model = Sequential() model.add(Dense(4, input_dim=4, kernel_initializer='normal', activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1, activation='linear')) model.summary()
The mean_squared_error (mse) and mean_absolute_error (mae) are our loss functions – i.e. an estimate of how accurate the neural network is in predicting the test data. We can see that with the validation_split set to 0.2, 80% of the training data is used to test the model, while the remaining 20% is used for testing purposes.
model.compile(loss='mse', optimizer='adam', metrics=['mse','mae']) model.fit(X_train, y_train, epochs=150, batch_size=50, verbose=1, validation_split=0.2)
From the output, we can see that the more epochs are run, the lower our MSE and MAE become, indicating improvement in accuracy across each iteration of our model.
The full output can be viewed at the Github repository.
Conclusion
In this tutorial, you have learned how to use Keras to create a regression-based neural network to conduct predictions. If you have any questions on this tutorial, please feel free to reach out to me anytime at [email protected].
