读取数据及数据集区分
所使用的数据是血友病数据,如有需要,可在主页资源处获取,数据信息如下:
数据预处理及区分数据集代码如下(详细预处理说明见上篇文章--随机森林):
import pandas as pd
import numpy as np
hemophilia = pd.read_csv('D:/my_files/data.csv') #读取数据
#数值变量化为分类变量
hemophilia['hiv']=hemophilia['hiv'].astype(object)
hemophilia['factor']=hemophilia['factor'].astype(object)
new_hemophilia=pd.get_dummies(hemophilia,drop_first=True)
#drop_first=True--删去一列,如hiv,处理后为两列,都是01表示,但只保留一列就足够表示两种状态
new_data=new_hemophilia
from sklearn.model_selection import train_test_split
x = new_data.drop(['deaths'],axis=1) #删去标签列
X_train, X_test, y_train, y_test = train_test_split(x, new_data.deaths, test_size=0.3, random_state=0)
#区分数据集,70%训练集,30%测试集
决策树回归预测
#决策树回归
from sklearn.tree import DecisionTreeRegressor
from sklearn import metrics
clf = DecisionTreeRegressor(random_state=0)
clf.fit(X_train, y_train)
y_pred2 = clf.predict(X_test)
print('MSE of clf: %.3f' %metrics.mean_squared_error(y_test, y_pred2))
'''MSE of zero_gp: 0.503'''
支持向量机回归预测
from sklearn.svm import SVR
from sklearn import metrics
svm_model=SVR()
svm_model.fit(X_train, y_train)
y_pred1 = svm_model.predict(X_test)
print('MSE of SVR: %.3f' %metrics.mean_squared_error(y_test, y_pred1)) #%.3f表示保留三位小数
'''
MSE of SVR: 0.499'''