代码:
# 导入需要的库
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
import numpy as np
import math
#获取数据转为numpy数组
filename=pd.read_csv("C:/Users/86170/Desktop/exel/testdata.csv")
filename1=pd.read_csv("C:/Users/86170/Desktop/exel/test.csv")
sheet1=np.array(filename)
sheet2=np.array(filename1)
#分成特征与标签
le = LabelEncoder()
#label_mapping = {0: 'AD', 1: 'CN', 2: 'EMCI', 3: 'LMCI', 4: 'SMC'}
X=np.array(sheet1[1:10001,0:26])
Y=np.array(sheet1[1:10001,26:27])
new_X=np.array(sheet2[1:10001,0:26])
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
y_train=le.fit_transform(y_train)
y_test=le.fit_transform(y_test)
# 创建BP神经网络分类器
# 训练XGBoost分类器
model = xgb.XGBClassifier(hidden_layer_sizes=(100,200,30), max_iter=1000, random_state=42)
model.fit(X_train, y_train)
# xgb.plot_tree(model)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("精确度为:", accuracy)
# 神经网络预测
error1 = y_pred - y_test
error=abs(error1)
#print(abs(error))
#预测值代码
#predict_y = np.zeros(10)
predict_y=model.predict(new_X)
predict_y1=np.transpose(predict_y)
#求误差
#平均绝对误差
matrix_sum=0
for row in error:
matrix_sum+=sum(row)/10000
#matrix_sum=abs(matrix_sum)
print( "平均绝对误差为:",matrix_sum)
break
#均方误差
mse1=error*error.T/10000
mse2=0
for row in mse1:
mse2+=sum(row)
#matrix_sum=abs(matrix_sum)
print("均方误差为:",mse2)
break
#均方根误差
mse3=math.sqrt(matrix_sum)
print("均方根误差为:",mse3)
#打印预测结果
print("前100个预测结果为:")
for i in range(1,100):
print(predict_y1[i])
print(y_test.shape)
print(y_pred.shape)
# 真实值与预测值误差比较的绘图代码
#取3000个点太多
y_test1=np.array(y_test[1:101,:])
y_pred1=np.array(y_pred[1:101])
X = list(np.arange(-1, 1, 0.02))
plt.plot(X, y_test1)
plt.plot(X, y_pred1)
plt.xlabel("x") # x轴标签
plt.ylabel("ylabel") # y轴标签
plt.title("xgboost netural real and prediction") # 图标题
plt.show()
# 上面的代码首先计算混淆矩阵,然后使用 matplotlib 库中的 imshow 函数将混淆矩阵可视化,最后通过 text 函数在混淆矩阵上添加数字,并使用 show/savefig 函数显示图像。
2.结果
目前只出来准确率,但确实挺高的,达到了0.997。BPNN相同的深度下准确率是0.985。