In [1]:
#支持向量机 根据训练样本的分布搜索所有可能分类器中最佳的那个
from sklearn.datasets import load_iris
digits = load_iris()
In [2]:
digits.data.shape
Out[2]:
In [3]:
#切分训练集和测试集
from sklearn.cross_validation import train_test_split
In [4]:
X_train,Xtest,Y_Train,Y_test=train_test_split(digits.data,
digits.target,
test_size=0.25,
random_state=33)
In [5]:
Y_Train.shape
Out[5]:
In [6]:
Y_test.shape
Out[6]:
In [19]:
#导入标准化模块, 标准化数据
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsRegressor #导入K近邻回归器
In [8]:
ss = StandardScaler()
In [9]:
X_train = ss.fit_transform(X_train)
In [10]:
Xtest = ss.transform(Xtest)
In [20]:
uni_knr = KNeighborsRegressor(weights = 'uniform') #使用平均回归
uni_knr.fit(X_train, Y_Train)
uni_knr_y_predic = uni_knr.predict(Xtest)
In [21]:
dis_knr = KNeighborsRegressor(weights = 'distance') #使用距离加权回归
dis_knr.fit(X_train, Y_Train)
dis_knr_y_predic = dis_knr.predict(Xtest)
In [22]:
from sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error
In [23]:
print 'The Accuracy of uniform-weight of KNeighborsRegressor is',uni_knr.score(Xtest, Y_test)
print 'The Value of R-squared of uniform-weight of KNeighborsRegressor is',r2_score(Y_test, uni_knr_y_predic)
print 'The Value of mean_absolute_error of uniform-weight of KNeighborsRegressor is',mean_absolute_error(Y_test, uni_knr_y_predic)
print 'The Value of mean_squared_error of uniform-weight of KNeighborsRegressor is',mean_squared_error(Y_test, uni_knr_y_predic)
In [24]:
print 'The Accuracy of distance-weight of KNeighborsRegressor is',dis_knr.score(Xtest, Y_test)
print 'The Value of R-squared of distance-weight of KNeighborsRegressor is',r2_score(Y_test, dis_knr_y_predic)
print 'The Value of mean_absolute_error of distance-weight of KNeighborsRegressor is',mean_absolute_error(Y_test, dis_knr_y_predic)
print 'The Value of mean_squared_error of distance-weight of KNeighborsRegressor is',mean_squared_error(Y_test, dis_knr_y_predic)