# 数据获取
# 数据处理
# 特征工程
# 分割
# 预处理
# 降维
# 建立模型 - 模型调优import pandas as pd
del_selection import train_test_split
from sklearn.preprocessing import StandardScaler
ighbors import KNeighborsClassifier
del_selection import GridSearchCVdata = pd.read_csv('DS/wine/winequality-red.csv')
feature = data.iloc[:, :11]
target = data.iloc[:, 11:]
x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.2, random_state=0)trans = StandardScaler()
x_train = trans.fit_transform(x_train)
x_test = ansform(x_test)
y_train = y_train.values.ravel()
y_test = y_test.values.ravel()estimator = KNeighborsClassifier()
dric = {'n_neighbors': [14, 15, 16, 17, 18]}
estimator = GridSearchCV(estimator, param_grid=dric, cv=8)estimator.fit(x_train, y_train)print(estimator.score(x_test, y_test))
print(estimator.best_estimator_)
0.584375
KNeighborsClassifier(n_neighbors=14)
可见,knn算法的正确率并不高,但是代码简单,构建快速。
下面记录一下实战过程中遇到的问题:
1.对于报错UserWarning: The least populated class in y has only 8 members, which is less than n_splits=10.
这个报错在于我一开始将cv设置为10,单cv有自己选取数据的机制,对于每一个特征,在每一个分类中都要出现,有一个特征的一个值的出现次数只有8次,没有达到10次。无法折叠。
解决方法:
1.将数据复制多分拼接在一起,使该数字的出现次数增多
2.将k改为8
2.1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().
这个问题是,该函数所接受的target是一个(n,)shape的形式,而在pandas直接划分形成的数据的形式是二维数组也就是(n,1)的形式。
解决方法 (dataframe).values.ravel() 转换为(n,)的形式
本文发布于:2024-01-30 23:39:48,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170662919223669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |