当特征的数值范围差距较大时,需要对特征的数值进行归一化,防止某些属性的权重过大。(有时不需特征归一化)
from sklearn import preprocessingimport numpy as npx1 = np.random.randint(0,10,1000).reshape((1000,1))x2 = np.random.randint(0,100,1000).reshape((1000,1))x3 = np.random.randint(0,10000,1000).reshape((1000,1))X = np.concatenate([x1,x2,x3],axis=1)print X[:4][[ 0 78 3423] [ 7 35 963] [ 7 63 9945] [ 3 60 6516]]# 特征数值归一化print preprocessing.scale(X)[:4][[-1.59232736 0.96948157 -0.56718281] [ 0.83236081 -0.55950092 -1.40672255] [ 0.83236081 0.43611559 1.65862133] [-0.55317529 0.32944239 0.48838484]验证归一化的重要性# 生成分类数据进行验证from sklearn import datasetsimport matplotlib.pyplot as plt%matplotlib inline# 生成分类数据:# n_sample:样本个数、n_features:类别标签种类数X, y = datasets.make_classification(n_samples=300, n_features=2, n_redundant=0, n_informative=2, random_state=25, n_clusters_per_class=1, scale=100)plt.scatter(X[:,0], X[:,1], c=y)plt.show()在分割训练集和测试集后,测试集一般用于对最后选择的模型进行评分。而在选择模型的超参数的过程中,为验证/评价模型的好坏,需要在训练集中取出一定比例的样本作为验证集来评价某个模型的好坏,训练集中的其他样本用来训练模型。
为消除所选出来的验证集中的样本的特殊性,则需要将训练集中的每一份样本作为验证集,其他样本作为训练集来训练模型。若将训练集中的样本分为N分,最后会得到N个对该模型的评分,对这些评分取均值,即得到了交叉验证的评分。
交叉验证一般用来调整模型的超参数。
sklearn中的交叉验证
cross_val_score函数用于交叉验证,返回各个验证集的评价得分。
from sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.model_selection import cross_val_scoreimport matplotlib.pyplot as plt%matplotlib inlineiris = datasets.load_iris()X = iris.datay = iris.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3., random_state=5)以KNN模型为例# 使用KNN模型进行预测(K为超参数)from sklearn.neighbors import KNeighborsClassifier# 超参数K的范围k_range = range(1,31)# 交叉验证的评分集合cv_scores = []for k in k_range: knn = KNeighborsClassifier(k) # 构造模型 # 将训练集均分为10份 #cv: 交叉验证迭代器 scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='accuracy') # 分类问题使用 #scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='neg_mean_squared_error') # 回归问题使用 cv_scores.append(scores.mean()) # # print cv_scores# 可视化各个k值模型的交叉验证的平均分plt.plot(k_range,cv_scores)plt.xlabel('k')plt.ylabel('Accuracy')plt.show()过拟合:模型对于训练集数据拟合程度过当,以致太适合训练集数据而无法适应一般情况。即训练出来的模型在训练集上表现很好,在验证集/测试集上表现并不好。
欠拟合:模型在训练集/测试集上都表现得不是很好。
# 加载数据from sklearn.model_selection import learning_curvefrom sklearn.svm import SVCimport numpy as npdigits = datasets.load_digits()X = digits.datay = digits.target欠拟合情况# 绘制学习曲线(学习曲线:在不同训练数据量下对训练出来的模型进行评分)# gamma = 0.001train_sizes, train_scores, val_scores = learning_curve( SVC(gamma=0.001), X, y, cv=10, scoring='accuracy', train_sizes=[0.1, 0.25, 0.5, 0.75, 1])# train_sizes: 每次模型训练的数量# train_scores: 每次模型在训练集上的评分# val_scores:每次模型在验证集上的交叉验证评分# 求不同训练数据量下的评分的均值train_scores_mean = np.mean(train_scores, axis=1) # 行均值val_scores_mean = np.mean(val_scores, axis=1)# 绘制学习曲线plt.plot(train_sizes, train_scores_mean, 'o-', color='r', label='training')plt.plot(train_sizes, val_scores_mean, '*-', color='g', label='cross validation')plt.xlabel('training sample size')plt.ylabel('accuracy')plt.legend(loc='best')plt.show()新闻热点
疑难解答