データマイニング(DM)- Python - RNN
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
]
開始行:
「[[.NET 開発基盤部会 Wiki>http://dotnetdevelopmentinfras...
散布図
-[[戻る>ビジネス インテリジェンス(BI)]]
--[[CRISP-DM>データマイニング(DM)- CRISP-DM]]
--[[Excel>データマイニング(DM)- Excel]]
--[[KNIME>データマイニング(DM)- KNIME]]
--[[Python>データマイニング(DM)- Python]]
--[[Python - DL>データマイニング(DM)- Python - DL]]
---[[Python - DNN>データマイニング(DM)- Python - DNN]]
---[[Python - CNN>データマイニング(DM)- Python - CNN]]
---Python - RNN
--[[DataSet>データマイニング(DM)- DataSet]]
*目次 [#k011d5b3]
#contents
*概要 [#l6c3d2b0]
[[RNN>ニューラルネットワーク#sa1d8d21]]、[[LSTM>ニューラ...
*詳細 [#n7596bcf]
**時系列予測 [#cb8443fc]
***データ [#td586627]
https://github.com/AileenNielsen/TimeSeriesAnalysisWithPy...
-ロード
--ダウンロード
url = 'https://raw.githubusercontent.com/AileenNielsen/T...
from urllib import request
request.urlretrieve(url, './work/AirPassengers.csv')
--ロード
df = pd.read_csv('./work/AirPassengers.csv')
-確認
--先頭
df.head()
--後尾
df.tail()
--列名変更
df.columns = ['Month', 'Passengers']
--可視化
plt.plot(df['Passengers'])
plt.xticks(np.arange(0, 145, 12))
plt.grid()
plt.show()
--[[基本成分に分解>再帰型ニューラルネットワーク(RNN)#y1...
from statsmodels.tsa.seasonal import seasonal_decompose
sd = seasonal_decompose(df['Passengers'].values, period=...
sd.plot()
plt.show()
-準備
--型変換~
Kerasが扱える型に変換
data = df['Passengers'].values.astype('f')
--正規化
---しないと上手く学習できない。
---X・Yともに正規化するので、推論結果はscaleを掛けて戻す。
scale = data.max()
data /= scale
--[[説明系列と目的系列、目的系列の教師データ化>再帰型ニュ...
このケースでは説明系列 = 目的系列なので、
x = data[:-1]
y = data[1:]
print('x:',len(x))
print('y:', len(y))
--shape変換~
Kerasの時系列解析用にshape変換~
・ x : 説明系列の配列(複数の説明系列)の配列(バッチ)の...
・ y : 目的系列の配列(バッチ)の可能性で2次元
print('x:', np.shape(x), ' y:', np.shape(y))
x = x.reshape(len(x), 1, 1)
y = y.reshape(len(y), 1)
print('x:', np.shape(x), ' y:', np.shape(y))
--[[時系列を維持して訓練・テストのデータ分割>再帰型ニュー...
# 訓練データのサンプル数を指定
train_size = int(len(data) * 0.7)
# データの分割
x_train = x[:train_size]
x_test = x[train_size:]
y_train = y[:train_size]
y_test = y[train_size:]
# shapeを確認
print('x_train:', x_train.shape)
print('x_test :', x_test.shape)
print('y_train:', y_train.shape)
print('y_test :', y_test.shape)
***モデル [#zfe4a4f7]
-LSTMの定義
--30ユニットのLSTMの層 + Denseレイヤ = 1つの値を予測
--LSTM(units, batch_input_shape=batch_size, time_step, i...
---units: 中間層のノード数(中間層の出力次元数)
---batch_input_shape: 入力するデータの形状を指定~
・バッチサイズ~
・予測のタイムステップ~
・入力の次元(特徴量(説明系列)の数)
model = Sequential()
model.add(LSTM(30, batch_input_shape=(None, 1, 1))) # 中...
model.add(Dense(1)) # 回帰なので最後の出力値は1つ
--コンパイル~
回帰の損失関数は誤差二乗和
model.compile(loss='mean_squared_error', optimizer=Adam())
--確認
model.summary()
-学習
batch_size = 20
n_epoch = 200
hist = model.fit(x_train,
y_train,
epochs=n_epoch,
validation_data=(x_test, y_test),
verbose=0,
batch_size=batch_size)
-推論
y_pred = model.predict(x)
--出力の正規化を戻す関数
def pred_n_passengers(y_pred, scale, year, month):
index = ((year - 1949) * 12) + (month - 1) # 1949/1...
return y_pred[index] * scale # 正規化した値を元に戻...
--1960年4月の乗客数を予測
year = 1960
month = 4
print("org : ", data[((year - 1949) * 12) + (month - 1)]...
print("pred: ", pred_n_passengers(y_pred, scale, year, m...
-評価~
回帰なので正答率は出力しない。
--実測・予測を表示
plt.plot(data, color='blue') # 実測値
plt.plot(y_pred, color='red') # 予測値
plt.show()
--学習履歴を表示
def plot_history_loss(hist):
plt.plot(hist.history['loss'],label="loss for traini...
plt.plot(hist.history['val_loss'],label="loss for va...
plt.title('model loss')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(loc='best')
plt.show()
plot_history_loss(hist)
**... [#y99a0084]
*参考 [#de1d739f]
-作成中のコンテンツへのリンク - OSSコンソーシアム~
https://www.osscons.jp/joho108j0-537
**[[scikit-learn]] [#db4fb149]
**[[TensorFlow・Keras]] [#k48e732d]
**[[再帰型ニューラルネットワーク(RNN)]] [#x8d67225]
終了行:
「[[.NET 開発基盤部会 Wiki>http://dotnetdevelopmentinfras...
散布図
-[[戻る>ビジネス インテリジェンス(BI)]]
--[[CRISP-DM>データマイニング(DM)- CRISP-DM]]
--[[Excel>データマイニング(DM)- Excel]]
--[[KNIME>データマイニング(DM)- KNIME]]
--[[Python>データマイニング(DM)- Python]]
--[[Python - DL>データマイニング(DM)- Python - DL]]
---[[Python - DNN>データマイニング(DM)- Python - DNN]]
---[[Python - CNN>データマイニング(DM)- Python - CNN]]
---Python - RNN
--[[DataSet>データマイニング(DM)- DataSet]]
*目次 [#k011d5b3]
#contents
*概要 [#l6c3d2b0]
[[RNN>ニューラルネットワーク#sa1d8d21]]、[[LSTM>ニューラ...
*詳細 [#n7596bcf]
**時系列予測 [#cb8443fc]
***データ [#td586627]
https://github.com/AileenNielsen/TimeSeriesAnalysisWithPy...
-ロード
--ダウンロード
url = 'https://raw.githubusercontent.com/AileenNielsen/T...
from urllib import request
request.urlretrieve(url, './work/AirPassengers.csv')
--ロード
df = pd.read_csv('./work/AirPassengers.csv')
-確認
--先頭
df.head()
--後尾
df.tail()
--列名変更
df.columns = ['Month', 'Passengers']
--可視化
plt.plot(df['Passengers'])
plt.xticks(np.arange(0, 145, 12))
plt.grid()
plt.show()
--[[基本成分に分解>再帰型ニューラルネットワーク(RNN)#y1...
from statsmodels.tsa.seasonal import seasonal_decompose
sd = seasonal_decompose(df['Passengers'].values, period=...
sd.plot()
plt.show()
-準備
--型変換~
Kerasが扱える型に変換
data = df['Passengers'].values.astype('f')
--正規化
---しないと上手く学習できない。
---X・Yともに正規化するので、推論結果はscaleを掛けて戻す。
scale = data.max()
data /= scale
--[[説明系列と目的系列、目的系列の教師データ化>再帰型ニュ...
このケースでは説明系列 = 目的系列なので、
x = data[:-1]
y = data[1:]
print('x:',len(x))
print('y:', len(y))
--shape変換~
Kerasの時系列解析用にshape変換~
・ x : 説明系列の配列(複数の説明系列)の配列(バッチ)の...
・ y : 目的系列の配列(バッチ)の可能性で2次元
print('x:', np.shape(x), ' y:', np.shape(y))
x = x.reshape(len(x), 1, 1)
y = y.reshape(len(y), 1)
print('x:', np.shape(x), ' y:', np.shape(y))
--[[時系列を維持して訓練・テストのデータ分割>再帰型ニュー...
# 訓練データのサンプル数を指定
train_size = int(len(data) * 0.7)
# データの分割
x_train = x[:train_size]
x_test = x[train_size:]
y_train = y[:train_size]
y_test = y[train_size:]
# shapeを確認
print('x_train:', x_train.shape)
print('x_test :', x_test.shape)
print('y_train:', y_train.shape)
print('y_test :', y_test.shape)
***モデル [#zfe4a4f7]
-LSTMの定義
--30ユニットのLSTMの層 + Denseレイヤ = 1つの値を予測
--LSTM(units, batch_input_shape=batch_size, time_step, i...
---units: 中間層のノード数(中間層の出力次元数)
---batch_input_shape: 入力するデータの形状を指定~
・バッチサイズ~
・予測のタイムステップ~
・入力の次元(特徴量(説明系列)の数)
model = Sequential()
model.add(LSTM(30, batch_input_shape=(None, 1, 1))) # 中...
model.add(Dense(1)) # 回帰なので最後の出力値は1つ
--コンパイル~
回帰の損失関数は誤差二乗和
model.compile(loss='mean_squared_error', optimizer=Adam())
--確認
model.summary()
-学習
batch_size = 20
n_epoch = 200
hist = model.fit(x_train,
y_train,
epochs=n_epoch,
validation_data=(x_test, y_test),
verbose=0,
batch_size=batch_size)
-推論
y_pred = model.predict(x)
--出力の正規化を戻す関数
def pred_n_passengers(y_pred, scale, year, month):
index = ((year - 1949) * 12) + (month - 1) # 1949/1...
return y_pred[index] * scale # 正規化した値を元に戻...
--1960年4月の乗客数を予測
year = 1960
month = 4
print("org : ", data[((year - 1949) * 12) + (month - 1)]...
print("pred: ", pred_n_passengers(y_pred, scale, year, m...
-評価~
回帰なので正答率は出力しない。
--実測・予測を表示
plt.plot(data, color='blue') # 実測値
plt.plot(y_pred, color='red') # 予測値
plt.show()
--学習履歴を表示
def plot_history_loss(hist):
plt.plot(hist.history['loss'],label="loss for traini...
plt.plot(hist.history['val_loss'],label="loss for va...
plt.title('model loss')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(loc='best')
plt.show()
plot_history_loss(hist)
**... [#y99a0084]
*参考 [#de1d739f]
-作成中のコンテンツへのリンク - OSSコンソーシアム~
https://www.osscons.jp/joho108j0-537
**[[scikit-learn]] [#db4fb149]
**[[TensorFlow・Keras]] [#k48e732d]
**[[再帰型ニューラルネットワーク(RNN)]] [#x8d67225]
ページ名: