数据挖掘——月亮数据

2023-11-11 19:10
文章标签 数据 数据挖掘 月亮

本文主要是介绍数据挖掘——月亮数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、问题描述

月亮数据是sklearn工具库提供的一个数据集。它上用于分类和聚类算法的实践实验。图中每一个点是一条数据。其中(x1,x2)是特征组,颜色是标签值。    

二、实验目的

学习决策树和随机森林

三、实验内容

1.数据导入:采用自动生成的数据

2.数据预处理:使用库函数进行数据处理

四、实验结果及分析

原始数据:

Max_depth=2:

Max_depth = 5:

五、遇到的问题和解决方法

图像处理的时候不太懂,参考别人的做的。

六、完整代码

decisionTreeBase.py

import numpy as np
from machine_learning.homework.week10.TreeNode import Nodeclass DecisionTreeBase:def __init__(self, max_depth, feature_sample_rate, get_score):self.max_depth = max_depthself.feature_sample_rate = feature_sample_rateself.get_score = get_scoredef split_data(self, j, theta, X, idx):idx1, idx2 = list(), list()for i in idx:value = X[i][j]if value <= theta:idx1.append(i)else:idx2.append(i)return idx1, idx2def get_random_features(self, n):shuffled = np.random.permutation(n)size = int(self.feature_sample_rate * n)selected = shuffled[:size]return selecteddef find_best_split(self, X, y, idx):m, n = X.shapebest_score = float("inf")best_j = -1best_theta = float("inf")best_idx1, best_idx2 = list(), list()selected_j = self.get_random_features(n)for j in selected_j:thetas = set([x[j] for x in X])for theta in thetas:idx1, idx2 = self.split_data(j, theta, X, idx)if min(len(idx1), len(idx2)) == 0:continuescore1, score2 = self.get_score(y, idx1), self.get_score(y, idx2)w = 1.0 * len(idx1) / len(idx)score = w * score1 + (1 - w) * score2if score < best_score:best_score = scorebest_j = jbest_theta = thetabest_idx1 = idx1best_idx2 = idx2return best_j, best_theta, best_idx1, best_idx2, best_scoredef generate_tree(self, X, y, idx, d):r = Node()r.p = np.average(y[idx], axis=0)if d == 0 or len(idx) < 2:return rcurrent_score = self.get_score(y, idx)j, theta, idx1, idx2, score = self.find_best_split(X, y, idx)if score >= current_score:return rr.j = jr.theta = thetar.left = self.generate_tree(X, y, idx1, d - 1)r.right = self.generate_tree(X, y, idx2, d - 1)return rdef fit(self, X, y):self.root = self.generate_tree(X, y, range(len(X)), self.max_depth)def get_prediction(self, r, x):if r.left == None and r.right == None:return r.pvalue = x[r.j]if value <= r.theta:return self.get_prediction(r.left, x)else:return self.get_prediction(r.right, x)def predict(self, X):y = list()for i in range(len(X)):y.append(self.get_prediction(self.root, X[i]))return np.array(y)

decisionTreeClassifier.py

import numpy as np
from machine_learning.homework.week10.decisionTreeBase import DecisionTreeBasedef get_impurity(y, idx):p = np.average(y[idx], axis=0)return 1 - p.dot(p.T)def get_entropy(y, idx):_, k = y.shapep = np.average(y[idx], axis=0)return - np.log(p + 0.001 * np.random.rand(k)).dot(p.T)class DecisionTreeClassifier(DecisionTreeBase):def __init__(self, max_depth=0, feature_sample_rate=1.0):super().__init__(max_depth=max_depth,feature_sample_rate=feature_sample_rate,get_score=get_entropy)def predict_proba(self, X):return super().predict(X)def predict(self, X):proba = self.predict_proba(X)return np.argmax(proba, axis=1)

moon.py

from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from machine_learning.homework.week10.decisionTreeClassifier import DecisionTreeClassifier
from machine_learning.homework.week10.randomForestClassifier import RandomForestClassifier
from sklearn.metrics import accuracy_score
import numpy as npdef convert_to_vector(y):m = len(y)k = np.max(y) + 1v = np.zeros(m * k).reshape(m,k)for i in range(m):v[i][y[i]] = 1return vX, y = make_moons(n_samples=1000, noise=0.1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
plt.figure(0)
plt.axis([-1.5, 2.5, -0.75, 1.25 ])
plt.scatter(X_train[:, 0][y_train==0], X_train[:, 1][y_train==0], c='b', marker='o', s=10)
plt.scatter(X_train[:, 0][y_train==1], X_train[:, 1][y_train==1], c='r', marker='o', s=10)plt.show()tree = DecisionTreeClassifier(max_depth=5)
tree.fit(X_train, convert_to_vector(y_train))
y_pred = tree.predict(X_test)
print("decision tree accuracy= {}".format(accuracy_score(y_test, y_pred)))plt.figure(1)
x0s = np.linspace(-3, 4, 100)
x1s = np.linspace(-1, 6, 100)
x0, x1 = np.meshgrid(x0s, x1s)
W = np.c_[x0.ravel(), x1.ravel()]
u= tree.predict(W).reshape(x0.shape)
plt.axis([-1.5, 2.5, -0.75, 1.25 ])
plt.scatter(X_train[:, 0][y_train==0], X_train[:, 1][y_train==0], c='b', marker='o', s=30)
plt.scatter(X_train[:, 0][y_train==1], X_train[:, 1][y_train==1], c='g', marker='^', s=30)
plt.scatter(X_train[:, 0][y_train==2], X_train[:, 1][y_train==2], c='y', marker='s', s=30)
plt.contourf(x0, x1, u, c=u, alpha=0.2)
plt.show()
forest = RandomForestClassifier(max_depth=5, num_trees=100, feature_sample_rate=0.5, data_sample_rate=0.15)
forest.fit(X_train, convert_to_vector(y_train))
y_pred = forest.predict(X_test)
print("random forest accuracy= {}".format(accuracy_score(y_test, y_pred)))plt.figure(2)
u= forest.predict(W).reshape(x0.shape)
plt.axis([-1.5, 2.5, -0.75, 1.25 ])
plt.scatter(X_train[:, 0][y_train==0], X_train[:, 1][y_train==0], c='b', marker='o', s=30)
plt.scatter(X_train[:, 0][y_train==1], X_train[:, 1][y_train==1], c='g', marker='^', s=30)
plt.scatter(X_train[:, 0][y_train==2], X_train[:, 1][y_train==2], c='y', marker='s', s=30)
plt.contourf(x0, x1, u, c=u, alpha=0.2)plt.show()

randomForestClassifier.py

import numpy as np
from machine_learning.homework.week10.decisionTreeClassifier import DecisionTreeClassifierclass RandomForestClassifier:def __init__(self, num_trees, max_depth, feature_sample_rate,data_sample_rate, random_state=0):self.max_depth, self.num_trees = max_depth, num_treesself.feature_sample_rate = feature_sample_rateself.data_sample_rate = data_sample_rateself.trees = []np.random.seed(random_state)def get_data_samples(self, X, y):shuffled_indices = np.random.permutation(len(X))size = int(self.data_sample_rate * len(X))selected_indices = shuffled_indices[:size]return X[selected_indices], y[selected_indices]def fit(self, X, y):for t in range(self.num_trees):X_t, y_t = self.get_data_samples(X, y)model = DecisionTreeClassifier(max_depth=self.max_depth,feature_sample_rate=self.feature_sample_rate)model.fit(X_t, y_t)self.trees.append(model)def predict_proba(self, X):probas = np.array([tree.predict_proba(X) for tree in self.trees])return np.average(probas, axis=0)def predict(self, X):proba = self.predict_proba(X)return np.argmax(proba, axis=1)

TreeNode.py

# 树节点
class Node:j = Nonetheta = Nonep = Noneleft = Noneright = None

这篇关于数据挖掘——月亮数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/weixin_42562514/article/details/106693231
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/392228

相关文章

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

MyBatisPlus如何优化千万级数据的CRUD

《MyBatisPlus如何优化千万级数据的CRUD》最近负责的一个项目,数据库表量级破千万,每次执行CRUD都像走钢丝,稍有不慎就引起数据库报警,本文就结合这个项目的实战经验,聊聊MyBatisPl... 目录背景一、MyBATis Plus 简介二、千万级数据的挑战三、优化 CRUD 的关键策略1. 查

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

mysql中的数据目录用法及说明

《mysql中的数据目录用法及说明》:本文主要介绍mysql中的数据目录用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、版本3、数据目录4、总结1、背景安装mysql之后,在安装目录下会有一个data目录,我们创建的数据库、创建的表、插入的

Navicat数据表的数据添加,删除及使用sql完成数据的添加过程

《Navicat数据表的数据添加,删除及使用sql完成数据的添加过程》:本文主要介绍Navicat数据表的数据添加,删除及使用sql完成数据的添加过程,具有很好的参考价值,希望对大家有所帮助,如有... 目录Navicat数据表数据添加,删除及使用sql完成数据添加选中操作的表则出现如下界面,查看左下角从左

SpringBoot中4种数据水平分片策略

《SpringBoot中4种数据水平分片策略》数据水平分片作为一种水平扩展策略,通过将数据分散到多个物理节点上,有效解决了存储容量和性能瓶颈问题,下面小编就来和大家分享4种数据分片策略吧... 目录一、前言二、哈希分片2.1 原理2.2 SpringBoot实现2.3 优缺点分析2.4 适用场景三、范围分片

Redis分片集群、数据读写规则问题小结

《Redis分片集群、数据读写规则问题小结》本文介绍了Redis分片集群的原理,通过数据分片和哈希槽机制解决单机内存限制与写瓶颈问题,实现分布式存储和高并发处理,但存在通信开销大、维护复杂及对事务支持... 目录一、分片集群解android决的问题二、分片集群图解 分片集群特征如何解决的上述问题?(与哨兵模