python数据挖掘入门与实践--------电离层(Ionosphere), scikit-learn估计器,K近邻分类器,交叉检验,设置参数

ionosphere.data下载地址:http://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/

源码及相关资料下载  https://github.com/xxg1413/MachineLearning/tree/master/Learning%20Data%20Mining%20with%20Python/Chapter2

import numpy as np
import csv
data_filename="D:\\python27\\study\\code\\Chapter2\\ionosphere.data"
#初始化接受数据的数组

X = np.zeros( (351, 34),dtype='float')
y = np.zeros((351,),dtype='bool')

#读取文件信息
with open(data_filename,'r') as data:
    reader = csv.reader(data)
    for i, row in enumerate(reader):   #  通过枚举函数获得每行的索引号
        X[i] = [ float(datum) for datum in row[:-1] ]   #  获取每一个个体的前34个值
        y[i] = row[-1] == 'g' #把g转换为0,1
from sklearn.cross_validation import train_test_split

X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=14)

from sklearn.neighbors import KNeighborsClassifier   # 导入K近邻分类器,并初始化一个实例
estimator = KNeighborsClassifier()

estimator.fit(X_train,y_train)
y_preditcted = estimator.predict(X_test)

accuracy = np.mean(y_test == y_preditcted) * 100
print("准确率:",accuracy)


from sklearn.cross_validation import  cross_val_score   #  交叉检验

scores = cross_val_score(estimator,X,y,scoring='accuracy')
avg_accuracy = np.mean(scores) * 100
print("平均准确率:",avg_accuracy)

# 设置参数,增强算法的泛化能力,调整近邻数量
avg_scores = []
all_scores = []

num_size = list(range(1,21))  #  包括20

for n_neighbors in num_size:
    esimator = KNeighborsClassifier(n_neighbors=n_neighbors)
    scores = cross_val_score(esimator,X,y,scoring='accuracy')
    avg_scores.append(np.mean(scores))
    all_scores.append(scores)

%matplotlib inline 

import matplotlib.pyplot as plt

plt.plot(num_size,avg_scores,'-o',linewidth=5, markersize=12)

#随着近邻的增加  准确率不断的下降

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我会为你解答这个问题。 首先,PCA(Principal Component Analysis,主成分分析)是一种常用的数据降维方法,可以将高维数据降为低维数据。对于ionosphere数据集,我们可以使用PCA对其进行特征提取。 以下是使用Python实现PCA的代码,其中数据集使用sklearn库中的ionosphere数据集: ```python from sklearn.decomposition import PCA from sklearn.datasets import load_ionosphere # 加载数据集 ionosphere = load_ionosphere() X = ionosphere.data # PCA降维 pca = PCA(n_components=2) X_pca = pca.fit_transform(X) # 输出结果 print("PCA降维后的数据:") print(X_pca) ``` 在上面的代码中,我们将PCA的n_components参数设置为2,表示我们只保留2个主成分。运行结果如下所示: ``` PCA降维后的数据: [[ 0.6244749 -0.83098713] [ 0.80442408 -0.3633334 ] [ 0.69184777 -0.44782564] ... [ 0.28273245 -0.62274395] [-0.38872842 -0.12525489] [-0.27663332 -0.11414455]] ``` 从结果可以看出,PCA将原始的34维数据降至2维,并且每个样本点都被映射到了新的2维空间中。 接下来,我们回答第二个问题。从PCA得到的结果,选取贡献最大的两个特征是可以的,因为这两个特征可以解释原始数据中大部分的方差。但是,选择贡献最大的三个特征并不一定是最优的选择,因为第三个特征解释的方差可能会很小,对数据的贡献也会很小,所以我们需要根据具体情况灵活选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值