File size: 1,321 Bytes
5b241a7
 
 
 
 
 
 
 
 
 
 
3eb9674
5b241a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import confusion_matrix, precision_score, recall_score, accuracy_score, f1_score
import numpy as np
def my_evaluation(y, pred):
  # 正解と予測値を入れると自動で評価してくれます。
  print('混同行列:')
  print(confusion_matrix(y, pred))
  accuracy = accuracy_score(y, pred)

  print("正解率: %.3f" % accuracy)

  if len(np.unique(y))==2:
    precision = precision_score(y, pred)
    recall = recall_score(y, pred)
    f1 = f1_score(y, pred)
    print("精度: %.3f" % precision)
    print("再現率: %.3f" % recall)
    print("F1スコア: %.3f" % f1)


# 万能関数
def my_model(X_train, X_test, y_train, y_test, model, name=''):
  # モデル訓練
  model.fit(X_train, y_train)

  pred = model.predict(X_test)# 予測
  # モデル評価
  print(f'モデル名:{name}')
  my_evaluation(y_test, pred)
  return model

def my_best_model(X_train, X_test, y_train, y_test, model,params, name=''):
  # モデル訓練
  # 基礎モデル、パラメーター集合
  models = GridSearchCV(model, params)
  models.fit(X_train, y_train)

  best_model = models.best_estimator_
  pred = best_model.predict(X_test)# 予測
  # モデル評価
  print(f'モデル名:{name}')
  my_evaluation(y_test, pred)
  return best_model