0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

時系列モデルのさまざまな推定方法

Posted at

予測したy_predの値とブロック分けを行うための二つのリストから、ブロックごとの推定値を算出する。
この時、ブロックごとの推定値として、各時点の推定値(y_pred)の最頻値を用いている。

import numpy as np
from scipy.stats import mode
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.ensemble import RandomForestClassifier

def calculate_accuracy(y_true, y_pred):
    return np.mean(y_true == y_pred)

def block_majority_vote(y_pred, begin_list, end_list):
    block_predictions = []  # ブロックごとの予測を保存するリスト

    for begin, end in zip(begin_list, end_list):
        # ブロック内の予測を取得
        block_pred = y_pred[begin:end+1]
        
        # ブロック内の最頻値を計算
        block_mode = mode(block_pred)[0][0]
        block_predictions.append(block_mode)

    return block_predictions

# サンプルデータ
y_pred = np.array([1, 2, 2, 1, 1, 3, 3, 3, 4, 4])
begin_list = [0, 3, 5]
end_list = [2, 4, 8]
y_test = np.array([1, 1, 2, 2, 1, 3, 3, 4, 4, 4])

# ブロックごとの最頻値を計算
block_pred = block_majority_vote(y_pred, begin_list, end_list)
block_test = block_majority_vote(y_test, begin_list, end_list)

# ブロックごとの精度を計算
accuracies = [calculate_accuracy(block_test[i], block_pred[i]) for i in range(len(begin_list))]

# 全体の精度を計算
overall_accuracy = calculate_accuracy(np.array(block_test).flatten(), np.array(block_pred).flatten())

# 混同行列を計算
confusion = confusion_matrix(np.array(block_test).flatten(), np.array(block_pred).flatten())

# ランダムフォレストを使って特徴量の重要度を計算(例)
X = np.random.rand(len(begin_list), 5)  # ダミーデータ、実際のデータに置き換えてください
y = np.random.choice([0, 1], size=len(begin_list))  # ダミーデータ、実際のデータに置き換えてください
rf_clf = RandomForestClassifier(n_estimators=100)
rf_clf.fit(X, y)
feature_importance = rf_clf.feature_importances_

# 結果を表示
print(f"Overall Accuracy: {overall_accuracy:.2f}")
print("Confusion Matrix:")
print(confusion)
print("Feature Importance:")
print(feature_importance)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?