回帰モデルの構築

Kerasを用いた回帰モデルの構築は、連続値(実数)を予測するタスクに適したニューラルネットワークモデルの設計を指します。例えば、住宅価格の予測、売上の予測、温度の推定などが回帰問題に該当します。

以下に、Kerasによる回帰モデル構築の流れと主要なポイントを詳しく説明します。


1. データの準備

回帰モデルでは、目的変数(出力)が連続値である必要があります。

python
import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # 例: 疑似データ(特徴量Xとターゲットy) X = np.random.rand(1000, 10) y = np.sum(X, axis=1) + np.random.normal(0, 0.1, 1000) # データ分割 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 標準化(スケーリング) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test)

2. モデルの構築

Sequentialモデルで全結合層(Dense)を使って構築します。出力層のユニット数は1、活性化関数はなしまたは**線形(activation='linear')**とします。

python
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense model = Sequential([ Dense(64, activation='relu', input_shape=(X_train.shape[1],)), Dense(64, activation='relu'), Dense(1) # 出力は1つの実数 ])

3. モデルのコンパイル

回帰問題では損失関数に**平均二乗誤差(mse平均絶対誤差(mae)**を使うのが一般的です。

python
model.compile(optimizer='adam', loss='mse', metrics=['mae'])

4. モデルの学習

学習時はmodel.fit()でデータを渡します。

python
history = model.fit( X_train, y_train, validation_split=0.2, epochs=100, batch_size=32, verbose=1 )

5. モデルの評価

学習後、テストデータで評価します。

python
loss, mae = model.evaluate(X_test, y_test) print(f"Mean Absolute Error: {mae}")

6. 予測の実行

予測値を取得するにはmodel.predict()を使用します。

python
predictions = model.predict(X_test)

7. 可視化(任意)

学習経過や予測結果をプロットして性能を確認します。

python
import matplotlib.pyplot as plt # 学習過程の可視化 plt.plot(history.history['mae'], label='MAE (Train)') plt.plot(history.history['val_mae'], label='MAE (Validation)') plt.xlabel('Epoch') plt.ylabel('MAE') plt.legend() plt.show()

まとめ

Kerasによる回帰モデルの構築は以下のポイントに注意します:

  • 出力層はユニット数1、活性化関数は線形。

  • 損失関数はmseまたはmae。

  • スケーリングを行うことで学習の安定性が向上。

  • 活性化関数にはReLUなどを中間層に用いるのが一般的。

生成日:2025/05/22