import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
url=r"C:\Users\zmj佳佳佳\Desktop\测试.csv"
df = pd.read_csv(url, header=None, low_memory=False)
df.columns = ["grade", "dti", "delinq_2yrs", "earliest_cr_line", "fico_range_low", "inq_last_6mths",
"mths_since_last_delinq", "pub_rec", "revol_bal", "revol_util", "mths_since_last_major_derog",
"tot_cur_bal", "open_acc_6m", "open_il_12m", "open_il_24m", "mths_since_rcnt_il", "open_rv_12m",
"open_rv_24m", "max_bal_bc", "all_util", "inq_last_12m", "acc_open_past_24mths", "avg_cur_bal",
"bc_open_to_buy", "mo_sin_old_il_acct", "mo_sin_old_rev_tl_op", "mo_sin_rcnt_rev_tl_op", "mo_sin_rcnt_tl",
"mort_acc", "mths_since_recent_bc_dlq", "mths_since_recent_inq", "mths_since_recent_revol_delinq",
"num_accts_ever_120_pd", "num_actv_bc_tl", "num_actv_rev_tl", "num_bc_sats", "num_bc_tl",
"num_rev_accts", "num_rev_tl_bal_gt_0", "num_tl_90g_dpd_24m", "num_tl_op_past_12m", "pct_tl_nvr_dlq",
"pub_rec_bankruptcies"]
df.info()
# 将数据集分为训练集和测试集
x, y = df.iloc[:, 1:].values, df.iloc[:, 0].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)
feat_labels = df.columns[1:]
forest = RandomForestClassifier(random_state=0,n_jobs=-1, class_weight="balanced")
forest.fit(x_train, y_train)
print("准确率:", forest.score(x_train, y_train))
predict_results=forest.predict(x_test)
print(accuracy_score(predict_results, y_test))
print(confusion_matrix(predict_results, y_test))