题目三:使用 numpy 编写的 CART 分类/回归树算法,并对 iris 数据集/boston 数据集进行预 测。 具体内容: (1)导入数据集。 (2)划分数据(分成训练集和数据集) (3)训练模型(参考程序模板:cart_numpy_template.py) (4)输出树模型。 (5)进行预测,评估模型性能。 拓展内容(选做): (1)尝试加入 TN样本数量阈值和 TG基尼指数阈值作为终止条件。 (2)尝试对离散特征进行分枝。

时间: 2024-01-29 21:02:53 浏览: 20
好的,让我为你解答一下这个问题。 首先,你需要下载数据集,iris 数据集可以从 sklearn 中导入,boston 数据集可以从 sklearn.datasets 中导入。导入数据集的代码如下: ```python from sklearn.datasets import load_iris, load_boston iris = load_iris() X_iris = iris.data y_iris = iris.target boston = load_boston() X_boston = boston.data y_boston = boston.target ``` 接下来,你需要将数据集划分为训练集和测试集。可以使用 sklearn.model_selection 中的 train_test_split 函数来实现。代码如下: ```python from sklearn.model_selection import train_test_split X_iris_train, X_iris_test, y_iris_train, y_iris_test = train_test_split(X_iris, y_iris, test_size=0.2, random_state=42) X_boston_train, X_boston_test, y_boston_train, y_boston_test = train_test_split(X_boston, y_boston, test_size=0.2, random_state=42) ``` 接下来,你可以使用 numpy 库来实现 CART 分类/回归树算法。参考程序模板:cart_numpy_template.py。在实现过程中,你可以加入 TN 样本数量阈值和 TG 基尼指数阈值作为终止条件,以提高模型的泛化能力。对于离散特征的分枝,可以使用决策树的信息增益或基尼指数来进行特征选择。这里只给出 CART 分类树的实现代码示例: ```python import numpy as np class CARTClassifier: def __init__(self, min_samples_leaf=1, min_impurity_decrease=0.0): self.min_samples_leaf = min_samples_leaf self.min_impurity_decrease = min_impurity_decrease def fit(self, X, y): self.n_classes_ = len(np.unique(y)) self.tree_ = self._build_tree(X, y) def predict(self, X): return np.array([self._predict(inputs) for inputs in X]) def _build_tree(self, X, y): if len(y) == 0: return None n_samples, n_features = X.shape n_labels = len(np.unique(y)) if n_labels == 1: return {'leaf': True, 'class': y[0]} if n_samples < self.min_samples_leaf: return {'leaf': True, 'class': np.argmax(np.bincount(y))} best_feature, best_threshold, best_impurity = self._best_split(X, y) if best_impurity == 0: return {'leaf': True, 'class': np.argmax(np.bincount(y))} left_idx = np.where(X[:, best_feature] <= best_threshold)[0] right_idx = np.where(X[:, best_feature] > best_threshold)[0] left_tree = self._build_tree(X[left_idx, :], y[left_idx]) right_tree = self._build_tree(X[right_idx, :], y[right_idx]) return {'leaf': False, 'feature': best_feature, 'threshold': best_threshold, 'left': left_tree, 'right': right_tree} def _best_split(self, X, y): best_feature = None best_threshold = None best_impurity = np.inf for feature_idx in range(X.shape[1]): thresholds = np.unique(X[:, feature_idx]) for threshold in thresholds: y_left = y[X[:, feature_idx] <= threshold] y_right = y[X[:, feature_idx] > threshold] impurity = self._gini_impurity(y_left, y_right) if impurity < best_impurity: best_feature = feature_idx best_threshold = threshold best_impurity = impurity if best_impurity < self.min_impurity_decrease: return None, None, 0 return best_feature, best_threshold, best_impurity def _gini_impurity(self, y_left, y_right): p_l = len(y_left) / (len(y_left) + len(y_right)) p_r = 1 - p_l gini_l = 1 - sum((np.bincount(y_left) / len(y_left)) ** 2) gini_r = 1 - sum((np.bincount(y_right) / len(y_right)) ** 2) return p_l * gini_l + p_r * gini_r def _predict(self, inputs): node = self.tree_ while not node['leaf']: if inputs[node['feature']] <= node['threshold']: node = node['left'] else: node = node['right'] return node['class'] ``` 最后,你可以输出树模型,进行预测,并评估模型性能。代码如下: ```python clf = CARTClassifier() clf.fit(X_iris_train, y_iris_train) print(clf.tree_) y_iris_pred = clf.predict(X_iris_test) iris_accuracy = np.sum(y_iris_pred == y_iris_test) / len(y_iris_test) print('Iris accuracy:', iris_accuracy) clf = CARTRegressor() clf.fit(X_boston_train, y_boston_train) print(clf.tree_) y_boston_pred = clf.predict(X_boston_test) boston_mse = np.mean((y_boston_pred - y_boston_test) ** 2) print('Boston MSE:', boston_mse) ``` 参考资料: 1. scikit-learn 官方文档:https://scikit-learn.org/stable/modules/tree.html 2. CART算法原理与实现:https://www.cnblogs.com/Jie-Meng/p/decisiion_tree_c4.5_CART.html 3. 决策树算法详解:https://www.jianshu.com/p/6bfcfc61a6c0

相关推荐

最新推荐

recommend-type

【K-means算法】{1} —— 使用Python实现K-means算法并处理Iris数据集

此处基于K-means算法处理Iris数据集 Kmeans.py模块: import numpy as np class KMeansClassifier(): """初始化KMeansClassifier类""" def __init__(self, k=3, initCent='random', max_iter=500): # 类的成员...
recommend-type

Python数据处理课程设计-房屋价格预测

鉴于此,我将根据比赛的数据,构建特征变量集,选取有代表性的特征变量,在已有数据的基础上,对数据进行处理,使用机器学习算法分析房价问题,选择预测模型将其用于预测测试集的房屋价格。 此外,无论是对于监管者...
recommend-type

微信小程序-番茄时钟源码

微信小程序番茄时钟的源码,支持进一步的修改。番茄钟,指的是把工作任务分解成半小时左右,集中精力工作25分钟后休息5分钟,如此视作种一个“番茄”,而“番茄工作法”的流程能使下一个30分钟更有动力。
recommend-type

激光雷达专题研究:迈向高阶智能化关键,前瞻布局把握行业脉搏.pdf

电子元件 电子行业 行业分析 数据分析 数据报告 行业报告
recommend-type

安享智慧理财测试项目Mock服务代码

安享智慧理财测试项目Mock服务代码
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。