昇思MindSpore学习笔记3-02热门LLM及其他AI应用--K近邻算法实现红酒聚类

摘要:

介绍了K近邻算法,记录了MindSporeAI框架使用部分wine数据集进行KNN实验的步聚和方法。包括环境准备、下载红酒数据集、加载数据和预处理、搭建模型、进行预测等。

一、KNN概念

1. K近邻算法K-Nearest-Neighbor(KNN)

用于分类和回归的非参数统计方法

 Cover、Hart于1968年提出

机器学习最基础的算法之一。

确定样本类别

        计算样本与所有训练样本的距离

        找出最接近的k个样本

        统计样本类别

        投票

        结果就是票数最多的类。

三个基本要素:

        K值,样本分类由K个邻居的“多数表决”确定

                K值太小容易产生噪声

                K值太大类别界限模糊

        距离度量,特征空间中两个样本间的相似度

                距离越小越相似

                Lp距离(p=2时,即为欧式距离)

                曼哈顿距离

                海明距离

        分类决策规则

                多数表决

                基于距离加权的多数表决(权值与距离成反比)

2.预测算法(分类)的流程

(1)找出距离目标样本x_test最近的k个训练样本,保存至集合N中;

(2)统计集合N中各类样本个数 Ci,i=1,2,3,...,c;

(3)最终分类结果为Ci最大的那个类(argmaxCi)。

  k取值重要。

                根据问题和数据特点来确定。

                带权重的k近邻算法

                        每个样本有不同的投票权重

3.回归预测

回归预测输出为所有邻居的标签均值

yi为k个目标邻居样本的标签值

带样本权重的回归预测函数:

  ωi为第个i样本的权重

4. 距离的定义

常用欧氏距离(欧几里得距离)

R^{n}空间中两点x和y之间的欧氏距离公式

注意将特征向量的每个分量归一化

        减少不同尺度的干扰

                大数值特征分量会淹没小数值特征分量

其它距离

        Mahalanobis距离

        Bhattacharyya距离

、环境配置

%%capture captured_output
# 实验环境已经预装了mindspore==2.2.14,如需更换mindspore版本,可更改下面mindspore的版本号
!pip uninstall mindspore -y
!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.2.14
# 查看当前 mindspore 版本
!pip show mindspore

输出:

Name: mindspore
Version: 2.2.14
Summary: MindSpore is a new open source deep learning training/inference framework that could be used for mobile, edge and cloud scenarios.
Home-page: https://www.mindspore.cn
Author: The MindSpore Authors
Author-email: contact@mindspore.cn
License: Apache 2.0
Location: /home/nginx/miniconda/envs/jupyter/lib/python3.9/site-packages
Requires: asttokens, astunparse, numpy, packaging, pillow, protobuf, psutil, scipy
Required-by: mindnlp

三、下载红酒数据集

1. Wine数据集

官网链接:UCI Machine Learning Repository

        http://archive.ics.uci.edu/dataset/109/wine

数据内容:

        意大利同一地区、三个不同品种葡萄酒化学分析结果。

        包括每种葡萄酒中所含13种成分的量:

Alcohol

酒精

Malic acid

苹果酸

Ash

Alcalinity of ash

灰的碱度

Magnesium

Total phenols

总酚

Flavanoids

类黄酮

Nonflavanoid phenols

非黄酮酚

Proanthocyanins

原花青素

Color intensity

色彩强度

Hue

色调

OD280/OD315 of diluted wines

稀释酒的OD280/OD315

Proline

脯氨酸

方式一,从Wine数据集官网下载wine.data文件。

方式二,从华为云OBS中下载wine.data文件。

Key

Value

Key

Value

Data Set Characteristics

Multivariate

Number of Instances

178

Attribute Characteristics

Integer, Real

Number of Attributes

13

Associated Tasks

Classification

Missing Values?

No

2.下载数据集

from download import download
​
# 下载红酒数据集
url = "https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/MachineLearning/wine.zip"  
path = download(url, "./", kind="zip", replace=True)

输出:

Downloading data from https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/MachineLearning/wine.zip (4 kB)

file_sizes: 100%|██████████████████████████| 4.09k/4.09k [00:00<00:00, 2.35MB/s]
Extracting zip file...
Successfully downloaded / unzipped to ./

四、数据读取与处理

1.加载数据

导入os、numpy、MindSpore、matplotlib等模块

context.set_context()配置运行模式、后端信息、硬件等

读取Wine数据集wine.data

查看部分数据。

%matplotlib inline
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
​
import mindspore as ms
from mindspore import nn, ops
​
ms.set_context(device_target="CPU")

with open('wine.data') as csv_file:
    data = list(csv.reader(csv_file, delimiter=','))
print(data[56:62]+data[130:133])

输出:

[['1', '14.22', '1.7', '2.3', '16.3', '118', '3.2', '3', '.26', '2.03', '6.38', '.94', '3.31', '970'],
 ['1', '13.29', '1.97', '2.68', '16.8', '102', '3', '3.23', '.31', '1.66', '6', '1.07', '2.84', '1270'],
 ['1', '13.72', '1.43', '2.5', '16.7', '108', '3.4', '3.67', '.19', '2.04', '6.8', '.89', '2.87', '1285'],
 ['2', '12.37', '.94', '1.36', '10.6', '88', '1.98', '.57', '.28', '.42', '1.95', '1.05', '1.82', '520'],
 ['2', '12.33', '1.1', '2.28', '16', '101', '2.05', '1.09', '.63', '.41', '3.27', '1.25', '1.67', '680'],
 ['2', '12.64', '1.36', '2.02', '16.8', '100', '2.02', '1.41', '.53', '.62', '5.75', '.98', '1.59', '450'],
 ['3', '12.86', '1.35', '2.32', '18', '122', '1.51', '1.25', '.21', '.94', '4.1', '.76', '1.29', '630'],
 ['3', '12.88', '2.99', '2.4', '20', '104', '1.3', '1.22', '.24', '.83', '5.4', '.74', '1.42', '530'],
 ['3', '12.81', '2.31', '2.4', '24', '98', '1.15', '1.09', '.27', '.83', '5.7', '.66', '1.36', '560']]

三类样本(共178条)

自变量X为数据集的13个属性

因变量Y为数据集的3个类别

取样本的某两个属性进行2维可视化

可以看到在某两个属性上样本的分布情况以及可分性。

X = np.array([[float(x) for x in s[1:]] for s in data[:178]], np.float32)
Y = np.array([s[0] for s in data[:178]], np.int32)
attrs = ['Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols',
         'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue',
         'OD280/OD315 of diluted wines', 'Proline']
plt.figure(figsize=(10, 8))
for i in range(0, 4):
    plt.subplot(2, 2, i+1)
    a1, a2 = 2 * i, 2 * i + 1
    plt.scatter(X[:59, a1], X[:59, a2], label='1')
    plt.scatter(X[59:130, a1], X[59:130, a2], label='2')
    plt.scatter(X[130:, a1], X[130:, a2], label='3')
    plt.xlabel(attrs[a1])
    plt.ylabel(attrs[a2])
    plt.legend()
plt.show()

2.数据预处理

将数据集按128:50划分为训练集(已知类别样本)和验证集(待验证样本):

train_idx = np.random.choice(178, 128, replace=False)
test_idx = np.array(list(set(range(178)) - set(train_idx)))
X_train, Y_train = X[train_idx], Y[train_idx]
X_test, Y_test = X[test_idx], Y[test_idx]

五、模型构建--计算距离

MindSpore算子

        tile

        square

        ReduceSum

        sqrt

        TopK

矩阵运算并行计算

        目标样本x和已分类训练样本X_train的距离

        top k近邻

class KnnNet(nn.Cell):
    def __init__(self, k):
        super(KnnNet, self).__init__()
        self.k = k
​
    def construct(self, x, X_train):
        #平铺输入x以匹配X_train中的样本数
        x_tile = ops.tile(x, (128, 1))
        square_diff = ops.square(x_tile - X_train)
        square_dist = ops.sum(square_diff, 1)
        dist = ops.sqrt(square_dist)
        #-dist表示值越大,样本就越接近
        values, indices = ops.topk(-dist, self.k)
        return indices
​
def knn(knn_net, x, X_train, Y_train):
    x, X_train = ms.Tensor(x), ms.Tensor(X_train)
    indices = knn_net(x, X_train)
    topk_cls = [0]*len(indices.asnumpy())
    for idx in indices.asnumpy():
        topk_cls[Y_train[idx]] += 1
    cls = np.argmax(topk_cls)
    return cls

、模型预测

验证KNN算法

k=5

验证精度接近80%

acc = 0
knn_net = KnnNet(5)
for x, y in zip(X_test, Y_test):
    pred = knn(knn_net, x, X_train, Y_train)
    acc += (pred == y)
    print('label: %d, prediction: %s' % (y, pred))
print('Validation accuracy is %f' % (acc/len(Y_test)))

输出:

label: 1, prediction: 1
label: 3, prediction: 3
label: 3, prediction: 3
label: 3, prediction: 3
label: 3, prediction: 3
label: 3, prediction: 3
label: 1, prediction: 1
label: 3, prediction: 1
label: 1, prediction: 1
label: 1, prediction: 2
label: 3, prediction: 3
label: 1, prediction: 1
label: 3, prediction: 3
label: 1, prediction: 1
label: 1, prediction: 1
label: 3, prediction: 2
label: 1, prediction: 1
label: 3, prediction: 3
label: 1, prediction: 1
label: 1, prediction: 3
label: 1, prediction: 1
label: 1, prediction: 1
label: 1, prediction: 3
label: 1, prediction: 1
label: 3, prediction: 2
label: 1, prediction: 1
label: 3, prediction: 2
label: 3, prediction: 2
label: 1, prediction: 1
label: 3, prediction: 1
label: 3, prediction: 1
label: 1, prediction: 1
label: 2, prediction: 3
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 3
label: 2, prediction: 2
label: 2, prediction: 3
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 3
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
label: 2, prediction: 2
Validation accuracy is 0.720000

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/767401.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

2024年下半年系统集成项目管理工程师使用新版教材,该如何备考?

2024年下半年&#xff0c;新版的《系统集成项目管理工程师教程》&#xff08;第3版&#xff09;将被系统集成项目管理工程师使用。许多考生可能会感到迷茫&#xff0c;不知道该如何复习。毕竟教材更新后&#xff0c;以往的资料和真题都变得无用&#xff0c;重点内容和考试方向也…

llm学习-3(向量数据库的使用)

1&#xff1a;数据读取和加载 接着上面的常规操作 加载环境变量---》获取所有路径---》加载文档---》切分文档 代码如下&#xff1a; import os from dotenv import load_dotenv, find_dotenvload_dotenv(find_dotenv()) # 获取folder_path下所有文件路径&#xff0c;储存在…

OV SSL证书年度成本概览:为企业安全护航的经济之选

在当今数字化时代&#xff0c;企业网站不仅是品牌展示的窗口&#xff0c;更是与客户沟通的桥梁。然而&#xff0c;随着网络威胁的不断升级&#xff0c;保护网站安全成为了企业不可忽视的任务。SSL证书&#xff0c;特别是OV SSL证书&#xff0c;因其对企业身份的严格验证&#x…

Halcon OCR字符识别(极坐标转换,字符识别)

Halcon OCR字符识别&#xff08;极坐标转换&#xff0c;字符识别&#xff09; 代码 * 1.加载图片 *************************************************** dev_close_window () read_image (Image, ./img) get_image_size (Image, Width, Height) dev_get_window (WindowHandle…

聚鼎贸易:装饰画开店教程新手入门

当艺术遇上商业&#xff0c;每一幕交易皆是文化的交流。本篇将引领有志于开设装饰画店铺的新手们&#xff0c;迈入创业的门槛&#xff0c;以独特的视角和步骤&#xff0c;探索如何成功经营一家装饰画店。 精选货源乃基石。货源的选取不仅反映店主的品味&#xff0c;更直接影响到…

NPDP|产品经理的沟通协调能力:塑造产品成功的核心力量

在快速发展的商业环境中&#xff0c;产品经理的角色愈发重要。他们不仅要负责产品的战略规划、需求管理、项目管理&#xff0c;更要与团队内外各方进行有效的沟通协调。那么&#xff0c;产品经理的沟通协调能力到底有多重要呢&#xff1f;本文将深入探讨这一话题。 沟通是产品成…

使用css做一个旋转的八卦图

使用css做一个旋转的八卦图 1, html部分 <div class"tai"><div class"bai"></div><div class"hei"></div> </div>2, css部分 .tai{width: 200px;height: 200px;border: 1px solid #000;background: linea…

【Python机器学习】模型评估与改进——回归指标

对于回归问题&#xff0c;可以像分类问题一样进行详细评估&#xff0c;例如&#xff0c;对目标值估计过高与目标值估计过低进行对比分析。 但是&#xff0c;对于我们见过的大多数应用来说&#xff0c;使用默认就足够了&#xff0c;它由所有回归器的score方法给出。业务决策有时…

全面详解菲律宾slots游戏本土网盟广告CPI流量效果分析

全面详解菲律宾slots游戏本土网盟广告CPI流量效果分析 一、引言 随着互联网的普及和移动设备的广泛应用&#xff0c;网络游戏行业迅速崛起&#xff0c;成为全球娱乐市场的一大热门。菲律宾作为东南亚地区的重要国家&#xff0c;其网络游戏市场也呈现出蓬勃的发展势头。在这样的…

AI数字人直播源码出售价格公布!

随着数字人行业的兴起&#xff0c;以数字人直播为代表的应用场景逐渐成为人们日常生活中不可分割的一部分&#xff0c;再加上艾媒研究数据显示&#xff0c;超五成以上的被调查群体的企业使用过虚拟人技术&#xff0c;超三成被调查群体的企业计划使用虚拟人技术等结论的公布&…

网友炸锅:这款iPhone壳竟能直接放保时捷车钥匙?

在当今这个个性化消费时代&#xff0c;高端智能手机及其配件已经成为了展示个人身份和品味的重要途径。最近&#xff0c;一款专为保时捷车主量身定制的iPhone手机壳&#xff0c;在互联网上引发了广泛的关注和讨论。 这款手机壳不仅在设计上凸显了保时捷的品牌logo&#xff0c;…

游戏工作室如何巧妙应对IP封禁风险?

游戏工作室在使用IP时&#xff0c;面临着封号的风险&#xff0c;因此需要采取一些防封技巧来保护自己的运营。以下是一些游戏工作室常用的防封技巧。 1. 多IP轮换 游戏工作室可以使用多个代理IP&#xff0c;并定期轮换它们。这样做可以减少单个IP被频繁访问同一游戏服务器而被…

for循环中list触发fast-fail或不触发的原理和方法

Iterable和Iterator Iterator接口位于的位置是java.util.Iterator&#xff0c;它主要有两个抽象方法供子类实现。hasNext()用来判断还有没有数据可供访问&#xff0c;next()用来访问下一个数据。 集合Collection不是直接去实现Iterator接口&#xff0c;而是去实现Iterable接口…

Pycharm设置远程解释器(本地代码+远程服务器环境)

Pycharm设置远程解释器(本地代码+服务器环境) Pycharm设置远程开发环境: 1.点击IDE左上角“文件”-》点击其中的设置 2:点击项目->点击添加解释器 3: 4根据提示填入远程服务器的IP地址,端口,和用户名: 5:连接上后选择现有环境: 6:选择刚才建立好的conda环境…

ubnutu20.04-vscode安装leetcode插件流程

1.在vscode插件商城选择安装leetcode 2.安装node.js 官网下载一个版本安装流程&#xff1a; ①tar -xvf node-v14.18.0-linux-x64.tar.xz ①sudo ln -s /app/software/nodejs/bin/npm /usr/local/bin/ ②ln -s /app/software/nodejs/bin/node /usr/local/bin/ 查看版本&…

G1 垃圾收集器

从 JDK1.9 开始默认 G1&#xff0c;应用在多处理器和大容量内存环境中。 基础概念 Region G1 给整一块Heap内存区域均匀等分了N个 Region&#xff0c;N 默认情况下是 2048。 Region的大小只能是1M、2M、4M、8M、16M或32M (1-32M,并且为2的指数)&#xff0c;比如-Xmx16g -Xms…

【Unity 角色控制器组件】

【Unity 角色控制器组件】 Character Controller&#xff1a; Unity 内置的一个组件&#xff0c;用于提供高级的物理控制&#xff0c;允许开发者控制角色的移动、跳跃和碰撞。 csharp csharp // 假设你已经有了一个带有Character Controller组件的游戏对象// 获取Character Co…

第十四章 路由器 OSPF 动态路由配置

实验目的 掌握 OSPF 协议的配置方法&#xff1a; 掌握查看通过动态路由协议 OSPF 学习产生的路由&#xff1b; 熟悉广域网线缆的链接方式&#xff1b; 实验背景 假设校园网通过一台三层交换机连到校园网出口路由器上&#xff0c; 路由器再和校园外的另一台路由器连接。…

Java高级重点知识点-19-Lambda

文章目录 Lambda表达式函数式编程思想Lambda表达式写法代码讲解 Lambda表达式 函数式编程思想 强调做什么&#xff0c;而不是以什么形式做。 以函数式接口Runnable为例讲解&#xff1a; public class LambdaDemo {public static void main(String[] args) {Runnable runnab…

relation-graph——数据组装+鼠标移入后的详情(自定义插槽的用法)——js技能提升

最近在写后台管理系统的时候&#xff0c;遇到一个需求&#xff0c;就是给我一些节点&#xff0c;让我渲染到页面上&#xff0c;效果图如下&#xff1a; 之前写过一篇文章关于relation-graph关系图组件http://t.csdnimg.cn/7BGYm的用法 还有一篇关于relation-graph——实现右击…