
ãç¡æå ¬éãChatGPTã§Pythonããã°ã©ãã³ã°ïŒããŒã¿åæã¢ã㪠ã®å®äŸïŒ20ïŒïŒã©ã³ãã ãã©ã¬ã¹ãåæïŒåé¡ïŒã¢ããªïŒ
ããœã³ã³ã«PythonãšVSCodeãå ¥ããã°ãç°¡åãªæäœã§åæã§ããŸããããããã¯ãäžèšã®èšäºã®ãïŒ-ïŒïŒïŒVSCodeã®åºæ¬çãªäœ¿ãæ¹ãããåç §ãã ãããïŒ è€æ°ã®ã³ãŒããããå Žåã®ããŸãšãæ¹ã¯ãïŒïŒïŒã©ã³ãã£ãŒã®äœæãããåç §ãã ããã ïŒ
ïŒãæ©èœ
æ©èœïŒïŒãæ°èŠã«åæå®è¡ã
ã»éžæããSQLiteã®baseããŒãã«ãã«ã€ããŠãããŒã«ãã¢ãŠãæ³ã§ ã©ã³ãã ãã©ã¬ã¹ãã®ã¢ãã«ãåŠç¿ãããèšç·ŽããŒã¿ãšãã¹ãããŒã¿ããããã®ã¹ã³ã¢ãåºåããããŸããåæã«ãäžè¬ã®å顿šã§ã®ã¹ã³ã¢ãåºåããã ãŠãŒã¶ãŒãæºè¶³ã§ããã¹ã³ã¢ãåºãå Žåã«ãã®åŠç¿æžã¢ãã«ãä¿åãããšãšãã«ããã®ç¹åŸŽééèŠåºŠãCSVã§åºåããã
æ©èœïŒïŒãæ¢ååæãå¥ããŒã¿ã«é©çšã
ã»pikleãã¡ã€ã«ã«ä¿åããããåŠç¿æžã®ãã©ã³ãã ãã©ã¬ã¹ãã®ã¢ãã«ããŠãŒã¶ãŒãæå®ããåãç®ç倿°ãšèª¬æå€æ°ãæã€å¥ã®SQLiteã®baseããŒãã«ã«é©çšããã¹ã³ã¢ãã¡ãã»ãŒãžããã¯ã¹ã§åºåãããšãšãã«ãCSVã§ãåºåããã
æ©èœïŒïŒãæ¢ååæãçšããŠçµæäºæž¬ã
ã»pikleãã¡ã€ã«ã«ä¿åããããåŠç¿æžã®ãã©ã³ãã ãã©ã¬ã¹ãã®ã¢ãã«ãçšããŠãŠãŒã¶ãŒãæå®ããåã説æå€æ°ãæã€å¥ã®SQLiteã®baseããŒãã«ã«é©çšããç®ç倿°ãèšç®ããäºæž¬çµæããå
ã®baseããŒãã«ã®å
šé
ç®ã«äºæž¬çµæãä»äžããCSVã®åœ¢ã§åºåããã
ïŒãç»é¢é·ç§»
å®è¡ãããšäžèšã®ãã€ã¢ãã°ãç«ã¡äžããã

ïŒïŒïŒæ°èŠã«åæå®è¡ãæ©èœ
ãæ°èŠã«åæå®è¡ããã¿ã³ãã¯ãªãã¯ãããšæ¬¡ã®ã¡ãã»ãŒãžãåºãã

ãOKããããšãåŠç¿çšããŒã¿ããŒã¹ãéžæãããã€ã¢ãã°ã衚瀺ãããã

ããŒã¿ããŒã¹ãéžæããéãããã¿ã³ãã¯ãªãã¯ãããšãäžèšã®ããžã¹ãã£ã¯ååž°åæã®æ¡ä»¶èšå®ãã€ã¢ãã°ãéãã

æ¡ä»¶ãèšå®ããŠãåæåŠçãå®è¡ããã¿ã³ãã¯ãªãã¯ãããšãçµæã®ã¡ãã»ãŒãžãåºãã

ãOKããã¯ãªãã¯ãããšãå šããŒã¿ã§åŠç¿ãçŽããããã§åŠç¿æžã¿ã¢ãã«ãä¿åãããã©ãããèããŠããã

ãã¯ãããã¯ãªãã¯ãããšã次ã®ã¡ãã»ãŒãžãåºåãããã

äžèšã®ãã©ã«ããèŠãŠã¿ããšæ¬¡ã®ããã«ãªã£ãŠããã

ãã©ã«ãã®äžã¯æ¬¡ã®ããã«ãªã£ãŠããã

random_forest_rules.txtãéããšäžèšã®å 容ã«ãªã£ãŠããã

ïŒïŒïŒæ¢ååæãå¥ããŒã¿ã«é©çšãæ©èœ
â»ãã®æ©èœã¯ããæ°èŠã«åæå®è¡ãã§ä¿åããåŠç¿æžã¢ãã«ãååšããŠããããšãåæã«ããŠããã
æåã®ã¡ãã¥ãŒã§ãæ¢ååæãå¥ããŒã¿ã«é©çšããã¿ã³ãã¯ãªãã¯ãããšæ¬¡ã®ã¡ãã»ãŒãžãåºåãããã

ãOKããã¯ãªãã¯ãããšãåŠç¿æžã¢ãã«ãéžæãããã€ã¢ãã°ã衚瀺ãããã

ã¢ãã«ãéžæããéãããã¿ã³ãã¯ãªãã¯ãããšããããé©çšããããŒã¿ããŒã¹ã®éžæãæ±ããã¡ãã»ãŒãžã衚瀺ãããã

ãOKããã¯ãªãã¯ãããšãããŒã¿ããŒã¹éžæçšã®ãã€ã¢ãã°ã衚瀺ãããã

ããŒã¿ããŒã¹ãéžæããŠãéãããã¯ãªãã¯ãããšãé©çšçµæãèšç®ããã¡ãã»ãŒãžã衚瀺ãããã

ãOKããã¯ãªãã¯ãããšããã®æ£è§£çãCSVåºåããããèããŠããã

ãã¯ãããã¯ãªãã¯ãããšä¿åããå Žæãç¥ãããŠããã

ïŒïŒïŒæ¢ååæãçšããŠçµæäºæž¬ãæ©èœ
â»ãã®æ©èœã¯ããæ°èŠã«åæå®è¡ãã§ä¿åããåŠç¿æžã¢ãã«ãååšããŠããããšãåæã«ããŠããã
æåã®ã¡ãã¥ãŒã§ãæ¢ååæãçšããŠçµæäºæž¬ããã¿ã³ãã¯ãªãã¯ãããšæ¬¡ã®ã¡ãã»ãŒãžãåºåãããã

ãOKããã¯ãªãã¯ãããšãåŠç¿æžã¢ãã«ãéžæãããã€ã¢ãã°ã衚瀺ãããã

ã¢ãã«ãéžæããéãããã¿ã³ãã¯ãªãã¯ãããšããããé©çšããŠçµæäºæž¬ãããããŒã¿ããŒã¹ã®éžæãæ±ããã¡ãã»ãŒãžã衚瀺ãããã

ãOKããã¯ãªãã¯ãããšãããŒã¿ããŒã¹éžæçšã®ãã€ã¢ãã°ã衚瀺ãããã

ããŒã¿ããŒã¹ãéžæããŠãéãããã¯ãªãã¯ãããšãäºæž¬çµæãèšç®ããŠCSVãšããŠåºåããæ¬¡ã®ã¡ãã»ãŒãžãåºåãããã

â»äºæž¬çµæãæåŸã®åã«åºåãããŠããã

å®éã«ç§ã䜿ã£ãŠããã³ãŒãããå
¬éããŸãã®ã§ãèå³ãããæ¹ã¯ã芧ã«ãªã£ãŠãã ããã
ãæ³šæãæ±ãããŒã¿çã«ãããšã©ãŒãåºãå ŽåããããšæããŸãããã®å Žåã¯ãChatGPTã«ããã°ã©ã ã®ãã¡ã€ã«èªäœãæ·»ä»ãããšã©ãŒã®å
容ããã³ããŒããŠäŒããããã§ãå¯Ÿå¿æ¹æ³ã»ä¿®æ£æ¹æ³ãèããŠãã ããã
ïŒ ããã°ã©ã ïŒpd_bunrui_tree_random_forest.pyïŒ
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import sqlite3
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from datetime import datetime
from sklearn.model_selection import train_test_split, GridSearchCV
# from sklearn.preprocessing import StandardScaler
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.ensemble import RandomForestClassifier #ã©ã³ãã ãã©ã¬ã¹ãã¢ãã«ã®ã€ã³ããŒã
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score, classification_report
import joblib
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
import pickle
import shutil
## â ãæ°èŠã«åæå®è¡ãïŒéžæããSQLiteã®baseããŒãã«ãã«ã€ããŠãããŒã«ãã¢ãŠãæ³ã§
## ã©ã³ãã ãã©ã¬ã¹ãã®ã¢ãã«ãåŠç¿ãããèšç·ŽããŒã¿ãšãã¹ãããŒã¿ããããã®ã¹ã³ã¢ã
##ãåºåããããŸããåæã«ãäžè¬ã®å顿šã§ã®ã¹ã³ã¢ãåºåããã
## ãŠãŒã¶ãŒãæºè¶³ã§ããã¹ã³ã¢ãåºãå Žåã«ãã®åŠç¿æžã¢ãã«ãä¿åãããšãšãã«ããã®
## ç¹åŸŽééèŠåºŠãCSVã§åºåããã
## â ãæ¢ååæãå¥ããŒã¿ã«é©çšãïŒpikleãã¡ã€ã«ã«ä¿åããããåŠç¿æžã®ãã©ã³ãã ãã©ã¬ã¹ã
## ãã®ã¢ãã«ããŠãŒã¶ãŒãæå®ããåãç®ç倿°ãšèª¬æå€æ°ãæã€å¥ã®SQLiteã®baseããŒãã«ã«é©çšãã
##ããã¹ã³ã¢ãã¡ãã»ãŒãžããã¯ã¹ã§åºåãããšãšãã«ãCSVã§ãåºåããã
## â ãæ¢ååæãçšããŠçµæäºæž¬ãïŒpikleãã¡ã€ã«ã«ä¿åããããåŠç¿æžã®ãã©ã³ãã ãã©ã¬ã¹ãã®
##ã ã¢ãã«ãçšããŠãŠãŒã¶ãŒãæå®ããåã説æå€æ°ãæã€å¥ã®SQLiteã®baseããŒãã«ã«é©çšãã
##ããç®ç倿°ãèšç®ããäºæž¬çµæããå
ã®baseããŒãã«ã®å
šé
ç®ã«äºæž¬çµæãä»äžããCSVã®åœ¢ã§åºåããã
##ãplot_treeã®æ¥æ¬èªåã¯äžèšã§ã_export.py ãã¡ã€ã«ãæ¢ããfontname="helvetica"ãã"Sans"ã«ä¿®æ£ããã
##ãimport sklearn.tree._export
##ãprint(sklearn.tree._export.__file__)
# ãã©ã«ããäœæãã颿°
def create_output_folder(db_path):
db_name = os.path.splitext(os.path.basename(db_path))[0]
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
folder_name = f"{timestamp}_{db_name}"
os.makedirs(folder_name, exist_ok=True)
return folder_name
# ãã©ã«ãåé€çšé¢æ°
def delete_output_folder(folder_path):
try:
shutil.rmtree(folder_path)
# messagebox.showinfo("åé€å®äº", "ã¢ãã«ä¿åãã©ã«ããåé€ããŸããã")
except Exception as e:
messagebox.showerror("ãšã©ãŒ", f"ãã©ã«ãã®åé€äžã«ãšã©ãŒãçºçããŸãã: {str(e)}")
# ã©ã³ãã ãã©ã¬ã¹ãåæãå®è¡ãã颿°
# def perform_decision_tree(db_path, target_column, explanatory_columns, output_folder, max_dep_bottom, max_dep_top, rdm_state, cl_weight):
def perform_random_forest(db_path, target_column, explanatory_columns, output_folder, n_estimators, max_depth, random_state):
# ããŒã¿ããŒã¹ããããŒã¿ãååŸ
conn = sqlite3.connect(db_path)
df = pd.read_sql("SELECT * FROM base", conn)
conn.close()
# æ¬ æå€ããã§ãã¯ããâ
â
missing_x_columns = [col for col in explanatory_columns if df[col].isnull().any()]
missing_y = df[target_column].isnull().any().any() # ç®ç倿°ãè€æ°åã®å Žåã«å¯Ÿå¿
if missing_x_columns or missing_y:
error_message = "以äžã®é
ç®ã«æ¬ æå€ããããŸã:\n"
if missing_x_columns:
error_message += f"説æå€æ°: {', '.join(missing_x_columns)}\n"
if missing_y:
error_message += f"ç®ç倿°: {', '.join(target_column)}\n" # target_columnããªã¹ãã®å Žåã«å¯Ÿå¿
messagebox.showerror("æ¬ æå€ãšã©ãŒ", error_message)
return
# ããŒã¿ïŒãèšç·ŽïŒæ€èšŒããŒã¿ãïŒããèšç·ŽããŒã¿ããšãæ€èšŒããŒã¿ãã«ïŒåå²
x = df[explanatory_columns]
y = df[target_column]
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=random_state)
# ã©ã³ãã ãã©ã¬ã¹ãã¢ãã«ã®åæå
model = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, random_state=random_state)
# ã©ã³ãã ãã©ã¬ã¹ãã¢ãã«ã®åŠç¿
model.fit(x_train, y_train)
# èšç·ŽããŒã¿ã§ã¹ã³ã¢ã®èšç®
train_score = model.score(x_train, y_train)
# èšç·ŽããŒã¿ã§ã®åçŸçãšé©åç
train_y_pred = model.predict(x_train)
train_report = classification_report(y_train, train_y_pred, target_names=[str(c) for c in model.classes_])
# æ€èšŒããŒã¿ã§ã¹ã³ã¢ã®èšç®
val_score = model.score(x_val, y_val)
# æ€èšŒããŒã¿ã§ã®åçŸçãšé©åç
val_y_pred = model.predict(x_val)
val_report = classification_report(y_val, val_y_pred, target_names=[str(c) for c in model.classes_])
# æ®éã®å顿šåæã«ã€ããŠãåãããŒã¿ã§åŠç¿ããèšç·ŽããŒã¿ãšæ€èšŒããŒã¿ã§ã®ã¹ã³ã¢ãèšç®
decision_tree = DecisionTreeClassifier(max_depth=max_depth, random_state=random_state)
decision_tree.fit(x_train, y_train)
dt_train_score = decision_tree.score(x_train, y_train)
dt_train_y_pred = decision_tree.predict(x_train)
dt_train_report = classification_report(y_train, dt_train_y_pred, target_names=[str(c) for c in decision_tree.classes_])
dt_val_score = decision_tree.score(x_val, y_val)
dt_val_y_pred = decision_tree.predict(x_val)
dt_val_report = classification_report(y_val, dt_val_y_pred, target_names=[str(c) for c in decision_tree.classes_])
# äžèšã®æ€èšŒçµæãã¡ãã»ãŒãžã§åºåïŒâ
ãããç®çããŒã¿ã®é
ç®ããšã«åçŸçãšé©åçã衚瀺ããããä¿®æ£ïŒ
result_message = (f"â
ã©ã³ãã ãã©ã¬ã¹ãã®çµæ:\n"
f"èšç·ŽããŒã¿ã§ã®æ£è§£ç: {train_score:.4f}\n\n"
f"èšç·ŽããŒã¿ã§ã®åçŸçãšé©åç:\n{train_report}\n\n"
f"æ€èšŒããŒã¿ã§ã®æ£è§£ç: {val_score:.4f}\n\n"
f"æ€èšŒããŒã¿ã§ã®åçŸçãšé©åç:\n{val_report}\n\n"
f"â
ïŒåèïŒåçŽãªå顿šã®çµæ:\n"
f"èšç·ŽããŒã¿ã§ã®æ£è§£ç: {dt_train_score:.4f}\n"
f"èšç·ŽããŒã¿ã§ã®åçŸçãšé©åç:\n{dt_train_report}\n\n"
f"æ€èšŒããŒã¿ã§ã®æ£è§£ç: {dt_val_score:.4f}\n\n"
f"æ€èšŒããŒã¿ã§ã®åçŸçãšé©åç:\n{dt_val_report}")
messagebox.showinfo("ã©ã³ãã ãã©ã¬ã¹ãåæã®çµæ", result_message)
# ã¢ãã«ä¿åã®éžæè¢ã衚瀺
if messagebox.askyesno("ã¢ãã«ä¿å", "å
šããŒã¿ã§åŠç¿ããªãããäžã§ãã¢ãã«ãä¿åããŸããïŒ"):
# å
šããŒã¿ïŒx, yïŒã§åŠç¿ããªãããã¹ã³ã¢ãšç¹åŸŽééèŠåºŠãèšç®ãçŽãã
model.fit(x, y)
final_score = model.score(x, y)
feature_importances = model.feature_importances_
# åŠç¿ããªãããã©ã³ãã ãã©ã¬ã¹ãã¢ãã«ããä¿å
model_data = {
'model': model,
'target_column': target_column,
'explanatory_columns': explanatory_columns
}
model_path = os.path.join(output_folder, "random_forest_model.pkl")
joblib.dump(model_data, model_path)
# å
šããŒã¿ã§ã®äºæž¬çµæãååŸ
y_pred = model.predict(x)
# å
šããŒã¿ã§ã®åçŸçãšé©åçãååŸ
report = classification_report(y, y_pred, target_names=[str(c) for c in model.classes_])
# ã¢ãã«ä¿åæã®æ£è§£çãåçŸçãšé©åçã®è¡šç€º
messagebox.showinfo("ä¿åå®äº", (f"ã¢ãã«ã {model_path} ã«ä¿åãããŸããã\n"
f"å
šããŒã¿ã§ã®æ£è§£ç: {final_score:.4f}\n\n"
f"åçŸçãšé©åç:\n{report}"))
# åããŒã¿ã»ããã®åçŸçãšé©åçãèšç®
train_report = classification_report(y_train, train_y_pred, output_dict=True)
val_report = classification_report(y_val, val_y_pred, output_dict=True)
all_report = classification_report(y, y_pred, output_dict=True)
# ã¹ã³ã¢ãå«ãDataFrameãäœæ
score_data = pd.DataFrame({
"Dataset": ["Train", "Validation", "All Data"],
"Score": [train_score, val_score, final_score]
})
# åçŸçãšé©åçã®åã¯ã©ã¹ã远å
for class_label in model.classes_:
score_data[f"Recall_{class_label}"] = [
train_report[class_label]['recall'],
val_report[class_label]['recall'],
all_report[class_label]['recall']
]
score_data[f"Precision_{class_label}"] = [
train_report[class_label]['precision'],
val_report[class_label]['precision'],
all_report[class_label]['precision']
]
# CSVã«ä¿å
score_csv_path = os.path.join(output_folder, "model_score.csv")
score_data.to_csv(score_csv_path, index=False, encoding='utf-8-sig')
# ç¹åŸŽééèŠåºŠããé
ç®åãå«ã㊠CSV ã«ä¿å
importance_df = pd.DataFrame({
'Feature': explanatory_columns,
'Importance': feature_importances
})
importance_csv_path = os.path.join(output_folder, "feature_importances.csv")
importance_df.to_csv(importance_csv_path, index=False, encoding='utf-8-sig')
# ã©ã³ãã ãã©ã¬ã¹ãã®èšå®æ¡ä»¶ãããã¹ãã§ä¿å
config_text = (f"ã©ã³ãã ãã©ã¬ã¹ãèšå®æ¡ä»¶:\n"
f"ç®ç倿°: {target_column}\n"
f"説æå€æ°: {', '.join(explanatory_columns)}\n"
f"n_estimators: {n_estimators}\n"
f"max_depth: {max_depth}\n"
f"random_state: {random_state}\n"
f"å
šããŒã¿ã§ã®æ£è§£ç: {final_score:.4f}\n\n"
f"åã¯ã©ã¹ã®åçŸçãšé©åç:\n")
# åã¯ã©ã¹ããšã«åçŸçãšé©åçã远å
for class_label in model.classes_:
config_text += (f"ã¯ã©ã¹ {class_label} - åçŸç: {all_report[str(class_label)]['recall']:.4f}, "
f"é©åç: {all_report[str(class_label)]['precision']:.4f}\n")
config_txt_path = os.path.join(output_folder, "random_forest_config.txt")
with open(config_txt_path, 'w', encoding='utf-8') as f:
f.write(config_text)
# ã©ã³ãã ãã©ã¬ã¹ãã¢ãã«ã®ã«ãŒã«ãããã¹ãã§ä¿å
rules_txt_path = os.path.join(output_folder, "random_forest_rules.txt")
with open(rules_txt_path, 'w', encoding='utf-8') as f:
for i, estimator in enumerate(model.estimators_):
tree_rules = tree.export_text(estimator, feature_names=explanatory_columns)
f.write(f"Tree {i+1}:\n{tree_rules}\n\n")
else:
delete_output_folder(output_folder) # ãã©ã«ããåé€
# messagebox.showinfo("ã¢ãã«ä¿å", "ã¢ãã«ã¯ä¿åãããŸããã§ããã")
# æ©æ¢°åŠç¿ããŠçµæãä¿åãã颿°
def execute_analysis():
info_message = (f"éžæããŒã¿ãå岿°ïŒã§ãïŒå²ãèšç·ŽããŒã¿ãïŒå²ãæ€èšŒããŒã¿ã«ãã\n"
f"ã©ã³ãã ãã©ã¬ã¹ãã§åæããŸãã\n\n"
f"ãŸãã¯ãåŠç¿å¯Ÿè±¡ã®ããŒã¿ããŒã¹ãéžæããŠãã ããã")
messagebox.showinfo("åŠçã®èª¬æ", info_message)
db_path = filedialog.askopenfilename(filetypes=[("SQLite DB", "*.db")])
if not db_path:
return
# æ°å€é
ç®ãååŸ
conn = sqlite3.connect(db_path)
df = pd.read_sql("SELECT * FROM base", conn)
conn.close()
numeric_columns = df.select_dtypes(include=['float64', 'int64']).columns.tolist()
# æ°å€ä»¥å€ã®é
ç®ãååŸ
non_numeric_columns = df.select_dtypes(exclude=['float64', 'int64']).columns.tolist()
# æ°å€ä»¥å€ã®é
ç®ã®æ
å ±ãååŸ
non_numeric_info = []
for col in non_numeric_columns:
value_counts = df[col].value_counts()
top_3 = value_counts.nlargest(3).index.tolist()
top_3_counts = value_counts.nlargest(3).tolist()
non_numeric_info.append((col, len(value_counts), top_3, top_3_counts))
# ãã€ã¢ãã°ãäœæ
dialog = tk.Toplevel()
dialog.title(f"ã©ã³ãã ãã©ã¬ã¹ãã®æ¡ä»¶èšå®ã察象DB: {db_path}")
# ç®ç倿°ã®éžæããªãŒãã¥ãŒ
tk.Label(dialog, text="ç®ç倿°ãéžæ").pack()
target_tree_frame = tk.Frame(dialog)
target_tree_frame.pack(fill=tk.BOTH, expand=True)
target_tree = ttk.Treeview(target_tree_frame, columns=("é
ç®å", "çš®é¡æ°", "äžäœ3é
ç®"), show="headings", selectmode="browse")
target_tree.heading("é
ç®å", text="é
ç®å")
target_tree.heading("çš®é¡æ°", text="çš®é¡æ°")
target_tree.heading("äžäœ3é
ç®", text="äžäœ3é
ç®")
# è¡ãäžè¡ããšã«èç·è²ã«ããããã®ã¿ã°ãèšå®
target_tree.tag_configure('oddrow', background='#afeeee') # èç·è²
target_tree.tag_configure('evenrow', background='#ffffff')
# éæ°å€é
ç®æ
å ±ãããªãŒãã¥ãŒã«æ¿å
¥
for idx, (col, count, top_3, top_3_counts) in enumerate(non_numeric_info):
top_3_text = ", ".join([f"{item}({cnt})" for item, cnt in zip(top_3, top_3_counts)])
tag = 'oddrow' if idx % 2 == 0 else 'evenrow'
target_tree.insert("", "end", values=(col, count, top_3_text), tags=(tag,))
# åã®å¹
ãèšå®
target_tree.column("é
ç®å", anchor="w", width=150) # ã«ã©ã ååã®å¹
ãèšå®
target_tree.column("çš®é¡æ°", anchor="center", width=70) # çš®é¡æ°åã®å¹
ãèšå®
target_tree.column("äžäœ3é
ç®", anchor="w", width=1000) # äžäœ3çš®é¡ãšãã®æ°åã®å¹
ãèšå®
# 瞊ã¹ã¯ããŒã«ããŒãšæšªã¹ã¯ããŒã«ããŒã®è¿œå
target_y_scrollbar = tk.Scrollbar(target_tree_frame, orient=tk.VERTICAL, command=target_tree.yview)
target_x_scrollbar = tk.Scrollbar(target_tree_frame, orient=tk.HORIZONTAL, command=target_tree.xview)
target_tree.configure(yscrollcommand=target_y_scrollbar.set, xscrollcommand=target_x_scrollbar.set)
# ããªãŒãã¥ãŒã®ãŠã£ãžã§ããããããã³ã°
target_y_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
target_x_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
target_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
view="soukan" # çžé¢è¡å衚瀺ã§ããïŒâ
ããã§åæ¿ããããïŒ
if view=="soukan": # çžé¢è¡å衚瀺ã®å Žå
# 説æå€æ°ã®éžæããªãŒãã¥ãŒïŒçžé¢è¡å衚瀺ïŒ
tk.Label(dialog, text="説æå€æ°ãéžæ").pack()
tree_frame = tk.Frame(dialog)
tree_frame.pack(fill=tk.BOTH, expand=True)
# çžé¢è¡åãèšç®
correlation_matrix = df[numeric_columns].corr()
# çžé¢è¡åãããªãŒãã¥ãŒã§è¡šç€ºïŒå·ŠåŽã«é
ç®åã远å ïŒ
tree_view = ttk.Treeview(tree_frame, columns=("é
ç®å",) + tuple(numeric_columns), show="headings")
tree_view.heading("é
ç®å", text="é
ç®å")
for col in numeric_columns:
tree_view.heading(col, text=col)
# è¡ãäžè¡ããšã«èç·è²ã«ããããã®ã¿ã°ãèšå®
tree_view.tag_configure('oddrow', background='#afeeee') # èç·è²
tree_view.tag_configure('evenrow', background='#ffffff')
# çžé¢è¡åã®å€ãããªãŒãã¥ãŒã«æ¿å
¥ïŒå°æ°ç¹ä»¥äž3æ¡ç®ã§åæšäºå
¥ã亀äºã«è²ãèšå®ïŒ
for idx, row in enumerate(correlation_matrix.itertuples(), start=0):
rounded_values = tuple(round(val, 3) for val in row[1:])
tag = 'oddrow' if idx % 2 == 0 else 'evenrow'
tree_view.insert("", "end", values=(numeric_columns[idx],) + rounded_values, tags=(tag,))
# åå¹
ãæå®
tree_view.column("é
ç®å", width=150, anchor="w") # é
ç®åã®åå¹
ãé©åœã«èšå®
for col in numeric_columns:
tree_view.column(col, width=50, anchor="center") # çžé¢ä¿æ°ã®åå¹
ãé©åœã«èšå®
# 瞊ã¹ã¯ããŒã«ããŒãšæšªã¹ã¯ããŒã«ããŒã®è¿œå
y_scrollbar = tk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree_view.yview)
x_scrollbar = tk.Scrollbar(tree_frame, orient=tk.HORIZONTAL, command=tree_view.xview)
tree_view.configure(yscrollcommand=y_scrollbar.set, xscrollcommand=x_scrollbar.set)
y_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
x_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
else: # çµ±èšæ
å ±è¡šç€ºã®å Žå
# 説æå€æ°ã®éžæããªãŒãã¥ãŒïŒçµ±èšæ
å ±è¡šç€ºïŒâ
tk.Label(dialog, text="説æå€æ°ãéžæ").pack()
tree_frame = tk.Frame(dialog)
tree_frame.pack(fill=tk.BOTH, expand=True)
# æ°å€é
ç®ã®çµ±èšæ
å ±ãèšç®
stats_data = df[numeric_columns].agg(['mean', 'median', 'quantile', 'max', 'min', 'var', 'std']).T
stats_data['Q1'] = df[numeric_columns].quantile(0.25)
stats_data['Q3'] = df[numeric_columns].quantile(0.75)
# å°æ°ç¹ä»¥äž2æ¡ã«äžžãã
stats_data = stats_data.round(2)
stats_data['Q1'] = stats_data['Q1'].round(2)
stats_data['Q3'] = stats_data['Q3'].round(2)
# ããªãŒãã¥ãŒã§è¡šç€º
tree_view = ttk.Treeview(tree_frame, columns=("é
ç®å", "å¹³å", "äžå€®å€", "Q1", "Q3", "æå€§å€", "æå°å€", "忣", "æšæºåå·®"), show="headings")
tree_view.heading("é
ç®å", text="é
ç®å")
tree_view.heading("å¹³å", text="å¹³å")
tree_view.heading("äžå€®å€", text="äžå€®å€")
tree_view.heading("Q1", text="Q1")
tree_view.heading("Q3", text="Q3")
tree_view.heading("æå€§å€", text="æå€§å€")
tree_view.heading("æå°å€", text="æå°å€")
tree_view.heading("忣", text="忣")
tree_view.heading("æšæºåå·®", text="æšæºåå·®")
# è¡ãäžè¡ããšã«èç·è²ã«ããããã®ã¿ã°ãèšå®
tree_view.tag_configure('oddrow', background='#afeeee') # èç·è²
tree_view.tag_configure('evenrow', background='#ffffff')
# çµ±èšæ
å ±ãããªãŒãã¥ãŒã«æ¿å
¥
for idx, (col, row) in enumerate(stats_data.iterrows()):
tag = 'oddrow' if idx % 2 == 0 else 'evenrow'
tree_view.insert("", "end", values=(col, *row), tags=(tag,))
# åã®å¹
ãèšå®
tree_view.column("é
ç®å", anchor="w", width=150) # ã«ã©ã ååã®å¹
ãèšå®
tree_view.column("å¹³å", anchor="center", width=100)
tree_view.column("äžå€®å€", anchor="center", width=100)
tree_view.column("Q1", anchor="center", width=100)
tree_view.column("Q3", anchor="center", width=100)
tree_view.column("æå€§å€", anchor="center", width=100)
tree_view.column("æå°å€", anchor="center", width=100)
tree_view.column("忣", anchor="center", width=100)
tree_view.column("æšæºåå·®", anchor="center", width=100)
# 瞊ã¹ã¯ããŒã«ããŒãšæšªã¹ã¯ããŒã«ããŒã®è¿œå
y_scrollbar = tk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree_view.yview)
x_scrollbar = tk.Scrollbar(tree_frame, orient=tk.HORIZONTAL, command=tree_view.xview)
tree_view.configure(yscrollcommand=y_scrollbar.set, xscrollcommand=x_scrollbar.set)
# ããªãŒãã¥ãŒã®ãŠã£ãžã§ããããããã³ã°
y_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
x_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
tree_view.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# äœæããæ±ºå®æšã®æ° (n_estimators) ãå
¥å
tk.Label(dialog, text="äœæããæ±ºå®æšã®æ°(n_estimators)ãå
¥å").pack()
n_estimators_entry = tk.IntVar()
n_estimators_entry.set(100) # åæå€ã 100ãã«èšå®
n_estimators_entry = tk.Entry(dialog, textvariable=n_estimators_entry)
n_estimators_entry.pack()
# æšã®æ·±ãã®æå€§å€ (max_depth) ãå
¥å
tk.Label(dialog, text="æšã®æ·±ãã®æå€§å€(max_depth)ãå
¥å").pack()
max_depth_entry = tk.IntVar()
max_depth_entry.set(10) # åæå€ã 10ãã«èšå®
max_depth_entry = tk.Entry(dialog, textvariable=max_depth_entry)
max_depth_entry.pack()
# random_stateã®å
¥å
tk.Label(dialog, text="random_stateãå
¥å").pack()
rdm_state_entry = tk.IntVar()
rdm_state_entry.set(0) # åæå€ã0ã«èšå®
rdm_state_entry = tk.Entry(dialog, textvariable=rdm_state_entry)
rdm_state_entry.pack()
# åŠçã¡ãã¥ãŒã®éžæãªã¹ãããã¯ã¹
# tk.Label(dialog, text="åŠçæ¹æ³ãéžæ").pack()
# method_var = tk.StringVar(value="ã©ã³ãã ãã©ã¬ã¹ãåæ") # ããã©ã«ãå€
# method_dropdown = ttk.Combobox(dialog, textvariable=method_var, values=["ã©ã³ãã ãã©ã¬ã¹ãåæ", "äœæäžïŒïŒåããŸããïŒ", "äœæäžïŒïŒåããŸããïŒ"])
# method_dropdown.pack()
# åæåŠçãå®è¡ãã¿ã³
def on_execute():
target_item = target_tree.selection() # ç®ç倿°
selected_items = tree_view.selection() # 説æå€æ°
if not selected_items or not target_item:
messagebox.showwarning("ãšã©ãŒ", "ç®ç倿°ãšèª¬æå€æ°ãéžæããŠãã ããã")
return
target_column = [target_tree.item(item, "values")[0] for item in target_item]
explanatory_columns = [tree_view.item(item, "values")[0] for item in selected_items]
output_folder = create_output_folder(db_path)
# messagebox.showwarning("target_columnïŒ", target_column)
# messagebox.showwarning("cl_weightïŒ", cl_weight_entry.get())
# messagebox.showwarning("max_dep_bottomïŒ", max_dep_bottom_entry.get())
# messagebox.showwarning("max_dep_topïŒ", max_dep_top_entry.get())
# messagebox.showwarning("rdm_stateïŒ", rdm_state_entry.get())
n_estimators=int(n_estimators_entry.get())
max_depth=int(max_depth_entry.get())
rdm_state=int(rdm_state_entry.get())
# éžæãããåææ¹æ³ã«åºã¥ããŠåŠçãåå²
# selected_method = method_var.get()
# if selected_method == "ã©ã³ãã ãã©ã¬ã¹ãåæ":
perform_random_forest(db_path, target_column, explanatory_columns, output_folder, n_estimators, max_depth, rdm_state)
# elif selected_method == "äœæäžïŒïŒåããŸããïŒ":
# # ââåæã®åŠçã远å
# pass # å
·äœçãªåŠçã¯åŸã§è¿œå
# elif selected_method == "äœæäžïŒïŒåããŸããïŒ":
# # â â åæã®åŠçã远å
# pass # å
·äœçãªåŠçã¯åŸã§è¿œå
execute_button = tk.Button(dialog, text="åæåŠçãå®è¡", command=on_execute)
execute_button.pack(pady=10)
# æ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæãåãåºããå¥ã®ããŒã¿ã«é©çšãã颿°
def tekiyou_result():
# æ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæããä»åé©çšãããã®ãéžæãã
messagebox.showinfo("åŠç¿æžã¢ãã«ã®éžæ", "é©çšããã åŠç¿æžã¢ãã« ããéžæããŠãã ããã")
pkl_path = filedialog.askopenfilename(filetypes=[("PKL file", "*.pkl")])
if not pkl_path:
return
# éžæããæ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæãåãåºã
with open(pkl_path, 'rb') as file:
model_data = joblib.load(file)
model = model_data['model'] #ä¿åãããåŠç¿æžã®æ©æ¢°åŠç¿ã¢ãã«
# éžæããæ¢åã®æ©æ¢°åŠç¿ã®ã¢ãã«ã«ãä»åé©çšããããŒã¿ããŒã¹ãéžæãã
messagebox.showinfo("ããŒã¿ããŒã¹ã®éžæ", "éžæããåŠç¿æžã¢ãã«ãé©çšããã ããŒã¿ããŒã¹ ããéžæããŠãã ããã")
db_path = filedialog.askopenfilename(filetypes=[("SQLite DB", "*.db")])
if not db_path:
return
# ããŒã¿ããŒã¹ããããŒã¿ãååŸ
conn = sqlite3.connect(db_path)
df = pd.read_sql("SELECT * FROM base", conn)
conn.close()
# 説æå€æ°ãšç®ç倿°ãå«ãŸããŠããã確èª
explanatory_columns = model_data['explanatory_columns'] # 説æå€æ°
target_column = model_data['target_column'] # ç®ç倿°
# ããŒã¿ããŒã¹ã«å¿
èŠãªåãå«ãŸããŠããããã§ãã¯
# missing_columns = [col for col in [target_column] + explanatory_columns if col not in df.columns]
missing_columns = [col for col in target_column + explanatory_columns if col not in df.columns]
if missing_columns:
# äžè¶³ããŠããåãã¡ãã»ãŒãžã§è¡šç€º
missing_message = (f"éžæããããŒã¿ããŒã¹ã«å¿
èŠãªåãå«ãŸããŠããŸããã\n"
f"ã¢ãã«ã®ç®ç倿°: {target_column}\n"
f"ã¢ãã«ã®èª¬æå€æ°: {', '.join(explanatory_columns)}\n"
f"äžè¶³ããŠããå: {', '.join(missing_columns)}")
messagebox.showwarning("åã®äžè¶³", missing_message)
return
# 説æå€æ°ãšç®ç倿°ã®ããŒã¿ãååŸ
x = df[explanatory_columns]
y = df[target_column]
# æ¬ æå€ããã§ãã¯ããâ
â
missing_x_columns = [col for col in explanatory_columns if df[col].isnull().any()]
missing_y = df[target_column].isnull().any().any() # ç®ç倿°ãè€æ°åã®å Žåãèæ
®
if missing_x_columns or missing_y:
error_message = "以äžã®é
ç®ã«æ¬ æå€ããããŸã:\n"
if missing_x_columns:
error_message += f"説æå€æ°: {', '.join(missing_x_columns)}\n"
if missing_y:
error_message += f"ç®ç倿°: {', '.join(target_column)}\n"
messagebox.showerror("æ¬ æå€ãšã©ãŒ", error_message)
return
# ã¢ãã«ãé©çšããè©äŸ¡ãè¡ã
score = model.score(X=x,y=y)
# è©äŸ¡çµæã衚瀺ïŒâ
ãããç®çããŒã¿ã®é
ç®ããšã«åçŸçãšé©åçã衚瀺ããããä¿®æ£ïŒ
result_message = f"ãã®ããŒã¿ã§ã®æ£è§£ç: {score:.3f}"
messagebox.showinfo("ãã®ããŒã¿ã§ã®æ£è§£ç", result_message)
info_message = f"ãã®ããŒã¿ã§ã®æ£è§£çãCSVã«åºåããŸããïŒ"
if messagebox.askyesno("æ±ºå®æšã®ç¢ºèª", info_message):
# ã¹ã³ã¢çµæãCSVã«åºåïŒâ
ãããç®çããŒã¿ã®é
ç®ããšã«åçŸçãšé©åçã衚瀺ããããä¿®æ£ïŒ
output_folder = os.path.dirname(pkl_path)
score_csv_path = os.path.join(output_folder, "model_score.csv")
pd.DataFrame([{"Score": score}]).to_csv(score_csv_path, index=False, encoding='utf-8-sig')
messagebox.showinfo("ãã®ããŒã¿ã§ã®æ£è§£çã®ä¿åå®äº", f"ãã®ããŒã¿ã§ã®æ£è§£çã {score_csv_path} ã«ä¿åãããŸããã")
# pass # å
·äœçãªåŠçã¯åŸã§è¿œå
# æ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæãçšããŠã説æå€æ°ããŒã¿ããç®ç倿°ãäºæž¬ãã颿°
def tekiyou_yosoku():
# æ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæããä»åé©çšãããã®ãéžæãã
messagebox.showinfo("åŠç¿æžã¢ãã«ã®éžæ", "é©çšããã åŠç¿æžã¢ãã« ããéžæããŠãã ããã")
pkl_path = filedialog.askopenfilename(filetypes=[("PKL file", "*.pkl")])
if not pkl_path:
return
# éžæããæ¢åã®æ©æ¢°åŠç¿ã®ä¿åçµæãåãåºã
with open(pkl_path, 'rb') as file:
model_data = joblib.load(file)
model = model_data['model'] #sklearnã®ã¢ãã«
explanatory_columns = model_data['explanatory_columns'] # 説æå€æ°
target_column = model_data['target_column'] # ç®ç倿°
# éžæããæ¢åã®æ©æ¢°åŠç¿ã®ã¢ãã«ã«ãä»åé©çšããããŒã¿ããŒã¹ãéžæãã
messagebox.showinfo("ããŒã¿ããŒã¹ã®éžæ", "éžæããåŠç¿æžã¢ãã«ãé©çšããŠçµæäºæž¬ããã\nã ããŒã¿ããŒã¹ ããéžæããŠãã ããã")
db_path = filedialog.askopenfilename(filetypes=[("SQLite DB", "*.db")])
if not db_path:
return
# ããŒã¿ããŒã¹ããããŒã¿ãååŸ
conn = sqlite3.connect(db_path)
df = pd.read_sql("SELECT * FROM base", conn)
conn.close()
# ããŒã¿ããŒã¹ã«å¿
èŠãªèª¬æå€æ°åãå«ãŸããŠããããã§ãã¯
missing_columns = [col for col in explanatory_columns if col not in df.columns]
if missing_columns:
# äžè¶³ããŠããåãã¡ãã»ãŒãžã§è¡šç€º
missing_message = (f"éžæããããŒã¿ããŒã¹ã«å¿
èŠãªåãå«ãŸããŠããŸããã\n"
f"ã¢ãã«ã®èª¬æå€æ°: {', '.join(explanatory_columns)}\n"
f"äžè¶³ããŠããå: {', '.join(missing_columns)}")
messagebox.showwarning("åã®äžè¶³", missing_message)
return
# 説æå€æ°ã®ããŒã¿ãååŸ
x = df[explanatory_columns]
# æ¬ æå€ããã§ãã¯ããâ
â
missing_x_columns = [col for col in explanatory_columns if df[col].isnull().any()]
if missing_x_columns:
error_message = "以äžã®é
ç®ã«æ¬ æå€ããããŸã:\n"
error_message += f"説æå€æ°: {', '.join(missing_x_columns)}\n"
messagebox.showerror("æ¬ æå€ãšã©ãŒ", error_message)
return
# ã¢ãã«ãé©çšããŠäºæž¬
y_pred = model.predict(x)
# äºæž¬çµæãCSVãã¡ã€ã«ã«ä¿å
output_df = df.copy() # å
ã®ããŒã¿ããŒã¹ã®ãã¹ãŠã®åãå«ã
output_df[f"Predicted_{target_column}"] = y_pred # äºæž¬çµæåã远å
output_file_path = os.path.join(os.path.dirname(pkl_path), f"{os.path.splitext(os.path.basename(db_path))[0]}_predictions.csv")
output_df.to_csv(output_file_path, index=False, encoding='utf-8-sig')
messagebox.showinfo("äºæž¬å®äº", f"äºæž¬çµæã {output_file_path} ã«ä¿åãããŸããã")
# pass # å
·äœçãªåŠçã¯åŸã§è¿œå
# ã¡ã€ã³ãŠã£ã³ããŠ
root = tk.Tk()
root.geometry("300x250")
root.title("ã©ã³ãã ãã©ã¬ã¹ãåæããŒã«")
# æ°èŠåæå®è¡ãã¿ã³
analyze_button = tk.Button(root, text="æ°èŠã«åæå®è¡", command=execute_analysis)
analyze_button.pack(pady=20)
# åæçµæé©çšãã¿ã³
analyze_button = tk.Button(root, text="æ¢ååæãå¥ããŒã¿ã«é©çš", command=tekiyou_result)
analyze_button.pack(pady=20)
# åæé©çšäºæž¬ãã¿ã³
analyze_button = tk.Button(root, text="æ¢ååæãçšããŠçµæäºæž¬", command=tekiyou_yosoku)
analyze_button.pack(pady=20)
root.mainloop()