Skip to main content
3 / 3
本文に 22 文字追加
cubick
  • 2.1万
  • 5
  • 27
  • 64

家庭内の全体の電力データと3つの家電製品の電力から全体の電力データを予測

https://archive.ics.uci.edu/dataset/235/individual+household+electric+power+consumption

上記のサイトから取得できるデータセットを用いて電力データの「時系列予測」を行っていて、 'Global_active_power', 'Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3' の4つのデータから
'Global_active_power' の予測を行いたくPython環境でKerasのライブラリのLSTMを使い「時系列予測」を行っているのですが、4つのデータから1つのデータの予測のやり方がわからないです。
現在のコードが以下のようになっています。4つのデータから4つをそのまま予測しているようです。
どのようにしたら4つのデータから1つのデータを予測できるでしょうか。ご教授してもらえると幸いです。

参考にしているのは以下のサイトです。
https://www.kaggle.com/code/yassinesfaihi/lstm-time-series-household-power-consumption

時刻 t-1 から t-5 の間の 'Global_active_power', 'Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3' の計4つのデータから、時刻 t'Global_active_power' を予測したいと思っています。

# Import necessary libraries and packages
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Set floating point precision option for pandas
pd.set_option('display.float_format', lambda x: '%.4f' % x)

# Import seaborn library and set context and style
import seaborn as sns
sns.set_context("paper", font_scale=1.3)
sns.set_style('white')

# Import warnings and set filter to ignore warnings
import warnings
warnings.filterwarnings('ignore')

# Import time library
from time import time

# Import matplotlib ticker and scipy stats
import matplotlib.ticker as tkr
from scipy import stats

# Import statistical tools for time series analysis
from statsmodels.tsa.stattools import adfuller

# Import preprocessing from sklearn
from sklearn import preprocessing

# Import partial autocorrelation function from statsmodels
from statsmodels.tsa.stattools import pacf

# Enable inline plotting in Jupyter Notebook
%matplotlib inline

# Import math library
import math

# Import necessary functions from keras
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import *

# Import MinMaxScaler from sklearn
from sklearn.preprocessing import MinMaxScaler

# Import mean squared error and mean absolute error from sklearn
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error

# Import early stopping from keras callbacks
from keras.callbacks import EarlyStopping

#結果の読み出し(前回の続きから出力)
data = pd.read_csv('/content/drive/MyDrive/Research_folder/Data_set/Data_set_from_UCI/household_power_consumption_Edited.csv')
data.head(5)

dataset = data.loc[:,['Global_active_power','Sub_metering_1','Sub_metering_2','Sub_metering_3']]

dataset = dataset.values.astype('float32')

#Create an instance of the MinMaxScaler class to scale the values between 0 and 1
scaler = MinMaxScaler(feature_range=(0, 1))

#Fit the MinMaxScaler to the transformed data and transform the values
dataset = scaler.fit_transform(dataset)

train_size = int(len(dataset) * 0.80)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]

# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
    X, Y = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        X.append(a)
        Y.append(dataset[i + look_back, 0])
    return np.array(X), np.array(Y)

# reshape into X=t and Y=t+1
look_back = 30
X_train, Y_train = create_dataset(train, look_back)
X_test, Y_test = create_dataset(test, look_back)

# reshape input to be [samples, time steps, features]
X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))

# Defining the LSTM model
model = Sequential()

# Adding the first layer with 100 LSTM units and input shape of the data
model.add(LSTM(100, input_shape=(X_train.shape[1], X_train.shape[2])))

# Adding a dropout layer to avoid overfitting
model.add(Dropout(0.2))

# Adding a dense layer with 1 unit to make predictions
model.add(Dense(1))

# Compiling the model with mean squared error as the loss function and using Adam optimizer
model.compile(loss='mean_squared_error', optimizer='adam')

# Fitting the model on training data and using early stopping to avoid overfitting
history = model.fit(X_train, Y_train, epochs=20, batch_size=1240, validation_data=(X_test, Y_test),
                    callbacks=[EarlyStopping(monitor='val_loss', patience=4)], verbose=1, shuffle=False)

# Displaying a summary of the model
model.summary()

# make predictions
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)


pad_col = np.zeros(dataset.shape[1]-1)
def pad_array(val):
    return np.array([np.insert(pad_col, 0, x) for x in val])

train_predict = scaler.inverse_transform(pad_array(train_predict))
Y_train = scaler.inverse_transform(pad_array(Y_train))
test_predict = scaler.inverse_transform(pad_array(test_predict))
Y_test = scaler.inverse_transform(pad_array(Y_test))

aa=[x for x in range(200)]
# Creating a figure object with desired figure size
plt.figure(figsize=(20,6))

plt.tick_params(labelsize=20)

# Plotting the actual values in blue with a dot marker
plt.plot(aa, Y_test[0][:200], marker='.', label="actual", color='purple')

# Plotting the predicted values in green with a solid line
plt.plot(aa, test_predict[:,0][:200], '-', label="prediction", color='red')

# Removing the top spines
sns.despine(top=True)

# Adjusting the subplot location
plt.subplots_adjust(left=0.07)

# Labeling the y-axis
plt.ylabel('Global_active_power', size=22)

# Labeling the x-axis
plt.xlabel('Time step', size=22)

# Adding a legend with font size of 15
plt.legend(fontsize=22)

# Display the plot
plt.show()