Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
3
Indexable
Never
filenames = glob.glob(r'C:\Users\Winni\Desktop\正葳\portion\Device*.csv')
model = DecisionTreeClassifier()
# model = XGBClassifier()
method = "upsampled"
device = []
error_dic = {}
writer = pd.ExcelWriter('report.xlsx', engine = 'openpyxl')
writer2 = pd.ExcelWriter('report_device.xlsx', engine = 'openpyxl')
writer3 = pd.ExcelWriter('report_redandyellow.xlsx', engine = 'openpyxl')
report_dv = {}

for file in filenames:
    device_num = file[34:file[41:].find('_')+41]
    device.append(device_num)
    device = list(set(device))
for dv in device:
    yt = []
    yp = []
    report = {}
    print(f"---------------{dv} ==>predict------------------")
    df, cat ,error = get_device(filenames,dv)
    error_dic[dv] = error
    for i in cat:
        df, cat ,error = get_device(filenames,dv)
        df1 = creat_y(df,dv,target=i)
        report[i],y_test, y_pred= predic_category(df1,method,model,target = str(i)+'_y')
        yt+=(y_test)
        yp+=(y_pred)
    data = {}
    for i in report:
        new_data = {}
        for key, values in report[i].items():
            try:
                new_data.update({f'{key}_{inner_key}': inner_value for inner_key, inner_value in values.items()})
            except:
                new_data[key] = values
        data[i] = new_data
    report_dv = classification_report(yt, yp,output_dict=True)
    cm = confusion_matrix(yt, yp,labels=['green','yellow','red','blue'])
    class_labels = ['green','yellow','red','blue']
    ax = sns.heatmap(data = cm, annot= True,fmt="d", cmap="Blues", cbar=False)
    ax.set_xticklabels(class_labels)
    ax.set_yticklabels(class_labels)
    plt.xlabel('Predict')
    plt.ylabel('True')
    plt.title(f'{dv} Confusion Matrix')
    plt.show()

    result_dv = pd.DataFrame(report_dv)
    result_dv.to_excel(writer2, sheet_name = dv)
    result_df = pd.DataFrame(data)
    recall = result_df.loc[["red_recall","red_support","red_f1-score","red_precision","yellow_recall","yellow_support","yellow_f1-score","yellow_precision"],:]
    recall.to_excel(writer3,sheet_name = dv)
    result_df.to_excel(writer, sheet_name = dv)
    # result_df.to_csv(f"./report/{dv}_Report.csv")
    print(f"---------------{dv} ==>predict End---------------")

writer.close()
writer2.close()
writer3.close()