Example #1
0
    # OLS
    model = LinearRegression()  # モデルの宣言
    estimated_y_in_cv = pd.DataFrame(
        cross_val_predict(model,
                          t_train.iloc[:, 0:component],
                          autoscaled_y_train,
                          cv=fold_number))  # クロスバリデーション推定値の計算し、DataFrame型に変換
    estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean(
    )  # スケールをもとに戻す
    r2_in_cv = metrics.r2_score(y_train, estimated_y_in_cv)  # r2 を計算
    print(component, r2_in_cv)  # 成分数と r2 を表示
    r2_in_cv_all.append(r2_in_cv)  # r2 を追加
    components.append(component)  # 成分数を追加

# 成分数ごとの CV 後の r2 をプロットし、CV 後のr2が最大のときを最適成分数に
optimal_component_number = sample_functions.plot_and_selection_of_hyperparameter(
    components, r2_in_cv_all, 'number of components', 'cross-validated r2')
print('\nCV で最適化された成分数 :', optimal_component_number)

# PCA
pca = PCA(n_components=optimal_component_number)
pca.fit(autoscaled_x_train)
t_train = pd.DataFrame(
    pca.transform(autoscaled_x_train))  # トレーニングデータの主成分スコアの計算
t_train.index = x_train.index
t_test = pd.DataFrame(pca.transform(autoscaled_x_test))  # テストデータの主成分スコアの計算
t_test.index = x_test.index

# OLS
model = LinearRegression()  # モデルの宣言
model.fit(t_train, autoscaled_y_train)  # モデルの構築
    random_state=21,
    stratify=y)

# OOB (Out-Of-Bugs) による説明変数の数の割合の最適化
accuracy_oob = []
for index, x_variables_rate in enumerate(rf_x_variables_rates):
    print(index + 1, '/', len(rf_x_variables_rates))
    model_in_validation = RandomForestClassifier(
        n_estimators=rf_number_of_trees,
        max_features=int(max(math.ceil(x_train.shape[1] * x_variables_rate),
                             1)),
        oob_score=True)
    model_in_validation.fit(x_train, y_train)
    accuracy_oob.append(model_in_validation.oob_score_)
optimal_x_variables_rate = sample_functions.plot_and_selection_of_hyperparameter(
    rf_x_variables_rates, accuracy_oob, 'rate of x-variables',
    'accuracy for OOB')
print('\nOOB で最適化された説明変数の数の割合 :', optimal_x_variables_rate)

# RF
model = RandomForestClassifier(
    n_estimators=rf_number_of_trees,
    max_features=int(
        max(math.ceil(x_train.shape[1] * optimal_x_variables_rate), 1)),
    oob_score=True)  # RF モデルの宣言
model.fit(x_train, y_train)  # モデルの構築

# 説明変数の重要度
x_importances = pd.DataFrame(model.feature_importances_,
                             index=x_train.columns,
                             columns=['importance'])
    # CV による k の最適化
    accuracy_in_cv_all = [
    ]  # 空の list の変数を作成して、成分数ごとのクロスバリデーション後の 正解率 をこの変数に追加していきます
    ks = []  # 同じく k の値をこの変数に追加していきます
    for k in range(1, max_number_of_k + 1):
        model = KNeighborsClassifier(n_neighbors=k,
                                     metric='euclidean')  # k-NN モデルの宣言
        # クロスバリデーション推定値の計算し、DataFrame型に変換
        estimated_y_in_cv = pd.DataFrame(
            cross_val_predict(model, autoscaled_x, y, cv=fold_number))
        accuracy_in_cv = metrics.accuracy_score(y, estimated_y_in_cv)  # 正解率を計算
        print(k, accuracy_in_cv)  # k の値と r2 を表示
        accuracy_in_cv_all.append(accuracy_in_cv)  # r2 を追加
        ks.append(k)  # k の値を追加
    # k の値ごとの CV 後の正解率をプロットし、CV 後の正解率が最大のときを k の最適値に
    optimal_k = sample_functions.plot_and_selection_of_hyperparameter(
        ks, accuracy_in_cv_all, 'k', 'cross-validated accuracy')

    print('\nCV で最適化された k :', optimal_k, '\n')
    # k-NN
    model = KNeighborsClassifier(n_neighbors=optimal_k,
                                 metric='euclidean')  # モデルの宣言
elif method_name == 'svm':
    optimal_svm_gamma = optimal_ocsvm_gamma.copy()
    # CV による C の最適化
    model_in_cv = GridSearchCV(svm.SVC(kernel='rbf', gamma=optimal_svm_gamma),
                               {'C': svm_cs},
                               cv=fold_number,
                               verbose=2)
    model_in_cv.fit(autoscaled_x, y)
    optimal_svm_c = model_in_cv.best_params_['C']
    # CV による γ の最適化
Example #4
0
    random_state=21,
    stratify=y)

# クロスバリデーションによる木の深さの最適化
accuracy_cv = []
max_depthes = []
for max_depth in range(1, max_max_depth):
    model_in_cv = tree.DecisionTreeClassifier(
        max_depth=max_depth, min_samples_leaf=min_samples_leaf)
    estimated_y_in_cv = cross_val_predict(model_in_cv,
                                          x_train,
                                          y_train,
                                          cv=fold_number)
    accuracy_cv.append(metrics.accuracy_score(y_train, estimated_y_in_cv))
    max_depthes.append(max_depth)
optimal_max_depth = sample_functions.plot_and_selection_of_hyperparameter(
    max_depthes, accuracy_cv, 'maximum depth of tree', 'accuracy in CV')
print('\nCV で最適化された木の深さ :', optimal_max_depth)

# DT
model = tree.DecisionTreeClassifier(
    max_depth=optimal_max_depth, min_samples_leaf=min_samples_leaf)  # モデルの宣言
model.fit(x_train, y_train)  # モデルの構築

# トレーニングデータ・テストデータの推定、混同行列の作成、正解率の値の表示、推定値の保存
sample_functions.estimation_and_performance_check_in_classification_train_and_test(
    model, x_train, y_train, x_test, y_test)

# 決定木のモデルを確認するための dot ファイルの作成
with open('tree.dot', 'w') as f:
    if model.classes_.dtype == 'object':
        class_names = model.classes_
# オートスケーリング
autoscaled_x_train = (x_train - x_train.mean()) / x_train.std()
autoscaled_x_test = (x_test - x_train.mean()) / x_train.std()

# CV による k の最適化
accuracy_in_cv_all = []  # 空の list の変数を作成して、成分数ごとのクロスバリデーション後の 正解率 をこの変数に追加していきます
ks = []  # 同じく k の値をこの変数に追加していきます
for k in range(1, max_number_of_k + 1):
    model = KNeighborsClassifier(n_neighbors=k, metric='euclidean')  # k-NN モデルの宣言
    # クロスバリデーション推定値の計算し、DataFrame型に変換
    estimated_y_in_cv = pd.DataFrame(model_selection.cross_val_predict(model, autoscaled_x_train, y_train,
                                                                       cv=fold_number))
    accuracy_in_cv = metrics.accuracy_score(y_train, estimated_y_in_cv)  # 正解率を計算
    print(k, accuracy_in_cv)  # k の値と r2 を表示
    accuracy_in_cv_all.append(accuracy_in_cv)  # r2 を追加
    ks.append(k)  # k の値を追加

# k の値ごとの CV 後の正解率をプロットし、CV 後の正解率が最大のときを k の最適値に
optimal_k = sample_functions.plot_and_selection_of_hyperparameter(ks, accuracy_in_cv_all, 'k',
                                                                  'cross-validated accuracy')
print('\nCV で最適化された k :', optimal_k, '\n')

# k-NN
model = KNeighborsClassifier(n_neighbors=optimal_k, metric='euclidean')  # モデルの宣言
model.fit(autoscaled_x_train, y_train)  # モデルの構築

# トレーニングデータ・テストデータの推定、混同行列の作成、正解率の値の表示、推定値の保存
sample_functions.estimation_and_performance_check_in_classification_train_and_test(model, autoscaled_x_train, y_train,
                                                                                   autoscaled_x_test, y_test)
y[167:] = 'positive'

if method_name == 'dt':
    # クロスバリデーションによる木の深さの最適化
    accuracy_cv = []
    max_depthes = []
    for max_depth in range(1, max_max_depth):
        model_in_cv = tree.DecisionTreeClassifier(
            max_depth=max_depth, min_samples_leaf=min_samples_leaf)
        estimated_y_in_cv = cross_val_predict(model_in_cv,
                                              x,
                                              y,
                                              cv=fold_number)
        accuracy_cv.append(metrics.accuracy_score(y, estimated_y_in_cv))
        max_depthes.append(max_depth)
    optimal_max_depth = sample_functions.plot_and_selection_of_hyperparameter(
        max_depthes, accuracy_cv, 'maximum depth of tree', 'accuracy in CV')
    print('\nCV で最適化された木の深さ :', optimal_max_depth)
    # DT
    model = tree.DecisionTreeClassifier(
        max_depth=optimal_max_depth,
        min_samples_leaf=min_samples_leaf)  # モデルの宣言
    model.fit(x, y)  # モデルの構築
    # 決定木のモデルを確認するための dot ファイルの作成
    with open('tree.dot', 'w') as f:
        if model.classes_.dtype == 'object':
            class_names = model.classes_
        else:
            # クラス名が数値のときの対応
            class_names = []
            for class_name_number in range(0, model.classes_.shape[0]):
                class_names.append(str(model.classes_[class_name_number]))