ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测

目录

基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测

设计思路

输出结果

核心代码


相关文章
ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测
ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测实现

基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测

设计思路

输出结果

(149, 5) 5.1  3.5  1.4  0.2  Iris-setosa
0  4.9  3.0  1.4  0.2  Iris-setosa
1  4.7  3.2  1.3  0.2  Iris-setosa
2  4.6  3.1  1.5  0.2  Iris-setosa
3  5.0  3.6  1.4  0.2  Iris-setosa
4  5.4  3.9  1.7  0.4  Iris-setosa
(149, 5) Sepal_Length  Sepal_Width  Petal_Length  Petal_Width            type
0           4.5          2.3           1.3          0.3     Iris-setosa
1           6.3          2.5           5.0          1.9  Iris-virginica
2           5.1          3.4           1.5          0.2     Iris-setosa
3           6.3          3.3           6.0          2.5  Iris-virginica
4           6.8          3.2           5.9          2.3  Iris-virginica
切分点: 29
label_classes: ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
kNNDIY模型预测,基于原数据: 0.95
kNN模型预测,基于原数据预测: [0.96666667 1.         0.93333333 1.         0.93103448]
kNN模型预测,原数据PCA处理后: [1.         0.96       0.95918367]

核心代码

class KNeighborsClassifier Found at: sklearn.neighbors._classificationclass KNeighborsClassifier(NeighborsBase, KNeighborsMixin, SupervisedIntegerMixin, ClassifierMixin):"""Classifier implementing the k-nearest neighbors vote.Read more in the :ref:`User Guide <classification>`.Parameters----------n_neighbors : int, default=5Number of neighbors to use by default for :meth:`kneighbors` queries.weights : {'uniform', 'distance'} or callable, default='uniform'weight function used in prediction.  Possible values:- 'uniform' : uniform weights.  All points in each neighborhoodare weighted equally.- 'distance' : weight points by the inverse of their distance.in this case, closer neighbors of a query point will have agreater influence than neighbors which are further away.- [callable] : a user-defined function which accepts anarray of distances, and returns an array of the same shapecontaining the weights.algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'Algorithm used to compute the nearest neighbors:- 'ball_tree' will use :class:`BallTree`- 'kd_tree' will use :class:`KDTree`- 'brute' will use a brute-force search.- 'auto' will attempt to decide the most appropriate algorithmbased on the values passed to :meth:`fit` method.Note: fitting on sparse input will override the setting ofthis parameter, using brute force.leaf_size : int, default=30Leaf size passed to BallTree or KDTree.  This can affect thespeed of the construction and query, as well as the memoryrequired to store the tree.  The optimal value depends on thenature of the problem.p : int, default=2Power parameter for the Minkowski metric. When p = 1, this isequivalent to using manhattan_distance (l1), and euclidean_distance(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.metric : str or callable, default='minkowski'the distance metric to use for the tree.  The default metric isminkowski, and with p=2 is equivalent to the standard Euclideanmetric. See the documentation of :class:`DistanceMetric` for alist of available metrics.If metric is "precomputed", X is assumed to be a distance matrix andmust be square during fit. X may be a :term:`sparse graph`,in which case only "nonzero" elements may be considered neighbors.metric_params : dict, default=NoneAdditional keyword arguments for the metric function.n_jobs : int, default=NoneThe number of parallel jobs to run for neighbors search.``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.``-1`` means using all processors. See :term:`Glossary <n_jobs>`for more details.Doesn't affect :meth:`fit` method.Attributes----------classes_ : array of shape (n_classes,)Class labels known to the classifiereffective_metric_ : str or callbleThe distance metric used. It will be same as the `metric` parameteror a synonym of it, e.g. 'euclidean' if the `metric` parameter set to'minkowski' and `p` parameter set to 2.effective_metric_params_ : dictAdditional keyword arguments for the metric function. For most metricswill be same with `metric_params` parameter, but may also contain the`p` parameter value if the `effective_metric_` attribute is set to'minkowski'.outputs_2d_ : boolFalse when `y`'s shape is (n_samples, ) or (n_samples, 1) during fitotherwise True.Examples-------->>> X = [[0], [1], [2], [3]]>>> y = [0, 0, 1, 1]>>> from sklearn.neighbors import KNeighborsClassifier>>> neigh = KNeighborsClassifier(n_neighbors=3)>>> neigh.fit(X, y)KNeighborsClassifier(...)>>> print(neigh.predict([[1.1]]))[0]>>> print(neigh.predict_proba([[0.9]]))[[0.66666667 0.33333333]]See also--------RadiusNeighborsClassifierKNeighborsRegressorRadiusNeighborsRegressorNearestNeighborsNotes-----See :ref:`Nearest Neighbors <neighbors>` in the online documentationfor a discussion of the choice of ``algorithm`` and ``leaf_size``... warning::Regarding the Nearest Neighbors algorithms, if it is found that twoneighbors, neighbor `k+1` and `k`, have identical distancesbut different labels, the results will depend on the ordering of thetraining data.https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm"""@_deprecate_positional_argsdef __init__(self, n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs):super().__init__(n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, n_jobs=n_jobs, **kwargs)self.weights = _check_weights(weights)def predict(self, X):"""Predict the class labels for the provided data.Parameters----------X : array-like of shape (n_queries, n_features), \or (n_queries, n_indexed) if metric == 'precomputed'Test samples.Returns-------y : ndarray of shape (n_queries,) or (n_queries, n_outputs)Class labels for each data sample."""X = check_array(X, accept_sparse='csr')neigh_dist, neigh_ind = self.kneighbors(X)classes_ = self.classes__y = self._yif not self.outputs_2d_:_y = self._y.reshape((-1, 1))classes_ = [self.classes_]n_outputs = len(classes_)n_queries = _num_samples(X)weights = _get_weights(neigh_dist, self.weights)y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype)for k, classes_k in enumerate(classes_):if weights is None:mode, _ = stats.mode(_y[neigh_indk], axis=1)else:mode, _ = weighted_mode(_y[neigh_indk], weights, axis=1)mode = np.asarray(mode.ravel(), dtype=np.intp)y_pred[:k] = classes_k.take(mode)if not self.outputs_2d_:y_pred = y_pred.ravel()return y_preddef predict_proba(self, X):"""Return probability estimates for the test data X.Parameters----------X : array-like of shape (n_queries, n_features), \or (n_queries, n_indexed) if metric == 'precomputed'Test samples.Returns-------p : ndarray of shape (n_queries, n_classes), or a list of n_outputsof such arrays if n_outputs > 1.The class probabilities of the input samples. Classes are orderedby lexicographic order."""X = check_array(X, accept_sparse='csr')neigh_dist, neigh_ind = self.kneighbors(X)classes_ = self.classes__y = self._yif not self.outputs_2d_:_y = self._y.reshape((-1, 1))classes_ = [self.classes_]n_queries = _num_samples(X)weights = _get_weights(neigh_dist, self.weights)if weights is None:weights = np.ones_like(neigh_ind)all_rows = np.arange(X.shape[0])probabilities = []for k, classes_k in enumerate(classes_):pred_labels = _y[:k][neigh_ind]proba_k = np.zeros((n_queries, classes_k.size))# a simple ':' index doesn't work rightfor i, idx in enumerate(pred_labels.T): # loop is O(n_neighbors)proba_k[all_rowsidx] += weights[:i]# normalize 'votes' into real [0,1] probabilitiesnormalizer = proba_k.sum(axis=1)[:np.newaxis]normalizer[normalizer == 0.0] = 1.0proba_k /= normalizerprobabilities.append(proba_k)if not self.outputs_2d_:probabilities = probabilities[0]return probabilities

ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测daiding相关推荐

  1. ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测

    ML之kNNC:基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测 目录 基于iris莺尾花数据集(PCA处理+三维散点图可视化)利用kNN算法实现分类预测 设计思路 ...

  2. DL之PerceptronAdalineGD:基于iris莺尾花数据集利用Perceptron感知机和AdalineGD算法实现二分类

    DL之Perceptron&AdalineGD:基于iris莺尾花数据集利用Perceptron感知机和AdalineGD算法实现二分类 目录 基于iris莺尾花数据集利用Perceptron ...

  3. 莺尾花数据集--kNN分类

    Step1: 库函数导入 import numpy as np # 加载莺尾花数据集 from sklearn import datasets # 导入KNN分类器 from sklearn.neig ...

  4. k-近邻(应用sklearn的莺尾花数据集)

    kNN 的作用机制为 在目标周围选取最近k个点,这k个点哪种占比最大,就可以把这个目标分类到那个分类,即有分到相似属性多的类别.  该算法和回归,决策树不同之处是,回归和决策树是通过训练集确定参数,参 ...

  5. KNN实战莺尾花数据集

    0 前言 俗话说,实践才能出真理,能动手就不要逼逼,下面将利用莺尾花数据集实战KNN算法. 1 实战概述 首先,要介绍一下这个实战的整体思路:要做什么.怎么做!第一步,我们应该拿到数据集,了解数据集信 ...

  6. SVM训练莺尾花数据集

    SVM训练莺尾花数据集 代码在莺尾花数据集上训练SVM,数据集由莺尾花的测量值及其相应的物种标签组成.该模型使用70%数据用于训练,然后剩余部分进行测试.其中′fit′'fit'′fit′方法在训练集 ...

  7. ML之xgboostGBM:基于xgboostGBM算法对HiggsBoson数据集(Kaggle竞赛)训练(两模型性能PK)实现二分类预测

    ML之xgboost&GBM:基于xgboost&GBM算法对HiggsBoson数据集(Kaggle竞赛)训练(两模型性能PK)实现二分类预测 目录 输出结果 设计思路 核心代码 输 ...

  8. 莺尾花数据集–贝叶斯分类(day5)

    莺尾花数据集–贝叶斯分类 Step1: 库函数导入 import warnings warnings.filterwarnings('ignore') #忽略了警告错误的输出 import numpy ...

  9. ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本

    ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本 目录 基于波士顿房价数据集利用LiR和LightGBM算法进行模 ...

最新文章

  1. dispatch_queue_create(com.biostime.xxx, DISPATCH_QUEUE_SERIAL)的陷阱
  2. 在DB中存储图像-是或否?
  3. 1补码 2补码_8085微处理器中8位数字的1和2的补码
  4. Asterisk权威指南/第二章 Asterisk架构
  5. c语言有趣的软件,一个有趣的小程序
  6. 智能摄像头如何防范被破解确保安全?
  7. 【Pix4d精品教程】Pix4Dmapper完整航测内业操作流程手把手图文教程
  8. 多机器人系统实验室汇总
  9. flash player所有版本下载地址
  10. 从java9共享内存加载modules说起
  11. 方波的产生——555 产生方波
  12. html css3滤镜,CSS滤镜之Glow属性_css
  13. 别人教我学计算机的作文,我教舅妈学电脑优秀作文.doc
  14. 利用python画圆
  15. php篮球比赛,篮球数据API接口-【篮球比赛动画直播变化数据】API调用示例代码...
  16. 做第三方软件测评的意义
  17. ARMv7 GICv2 GenericTimer 实战演练
  18. 三菱编程软件GX Works2复制粘贴错位
  19. 钉钉企业内部应用开发php,钉钉企业内部应用开发心得
  20. 三人行网络教育计算机二,三人行老师电脑版

热门文章

  1. C++各大著名程序库
  2. 139. Word Break
  3. 12c:CREATE DATABASE——DBCA
  4. 项目:部署LNMP动态网站
  5. 用ASP实现隐藏链接方法
  6. 批处理命令 For循环命令详解!
  7. overload和override的区别
  8. python中的for循环
  9. HTML中引入CSS的方法
  10. 干货 | 携程异地多活-MySQL实时双向(多向)复制实践