决策树python代码 
时间: 2023-05-20 17:04:38 浏览: 23
以下是一个简单的决策树 Python 代码示例:
```python
from sklearn import tree
# 训练数据
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
# 创建决策树模型
clf = tree.DecisionTreeClassifier()
# 训练模型
clf = clf.fit(features, labels)
# 预测新数据
print(clf.predict([[160, 0]]))
```
这个代码示例使用 scikit-learn 库中的决策树分类器来训练一个简单的模型,然后使用模型来预测新的数据。在这个示例中,我们使用两个特征来预测一个水果是苹果还是橘子:重量和表面是否光滑。
相关问题
决策树python代码实现
决策树在Python中可以使用scikit-learn库来实现。以下是一个简单的决策树的Python代码示例:
```
# 导入所需的库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 在训练集上训练模型
clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = clf.predict(X_test)
# 计算模型的准确率
print("准确率:", metrics.accuracy_score(y_test, y_pred))
```
这段代码首先导入了所需的库,包括`datasets`用于加载数据集,`train_test_split`用于将数据集拆分为训练集和测试集,`DecisionTreeClassifier`用于创建决策树分类器,以及`metrics`用于计算模型的准确率。
然后,代码加载了一个经典的鸢尾花数据集作为示例数据。接下来,将数据集拆分为训练集和测试集,其中测试集占总数据集的30%。
然后,创建了一个决策树分类器对象`clf`,并使用训练集对模型进行训练。最后,使用测试集进行预测,并计算模型的准确率。
这只是一个简单的决策树的示例,你可以根据自己的需求对代码进行修改和扩展。
cart决策树python代码
下面是一个简单的 CART 决策树的 Python 实现:
```python
import numpy as np
class CARTDecisionTree:
def __init__(self, max_depth=10, min_samples_split=2):
self.max_depth = max_depth
self.min_samples_split = min_samples_split
def fit(self, X, y):
self.tree = self.build_tree(X, y)
def build_tree(self, X, y, depth=0):
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
# 检查是否应该停止分裂
if (depth >= self.max_depth or
n_labels == 1 or
n_samples < self.min_samples_split):
return np.argmax(np.bincount(y))
# 寻找最佳分割特征和阈值
best_feature, best_threshold = self.get_best_split(X, y, n_samples, n_features)
# 分割样本集并递归构建子树
left_indices = X[:, best_feature] < best_threshold
right_indices = X[:, best_feature] >= best_threshold
left_subtree = self.build_tree(X[left_indices], y[left_indices], depth+1)
right_subtree = self.build_tree(X[right_indices], y[right_indices], depth+1)
return {'feature': best_feature, 'threshold': best_threshold,
'left': left_subtree, 'right': right_subtree}
def get_best_split(self, X, y, n_samples, n_features):
best_gini = float('inf')
best_feature, best_threshold = None, None
# 遍历所有特征和阈值,找到最佳分割
for feature in range(n_features):
thresholds = np.unique(X[:, feature])
for threshold in thresholds:
left_indices = X[:, feature] < threshold
right_indices = X[:, feature] >= threshold
if (len(left_indices) == 0 or len(right_indices) == 0):
continue
gini = self.gini_index(y, left_indices, right_indices)
if gini < best_gini:
best_gini = gini
best_feature = feature
best_threshold = threshold
return best_feature, best_threshold
def gini_index(self, y, left_indices, right_indices):
n_left, n_right = len(left_indices), len(right_indices)
gini_left, gini_right = 0, 0
if n_left > 0:
labels_left, counts_left = np.unique(y[left_indices], return_counts=True)
gini_left = 1 - np.sum((counts_left / n_left) ** 2)
if n_right > 0:
labels_right, counts_right = np.unique(y[right_indices], return_counts=True)
gini_right = 1 - np.sum((counts_right / n_right) ** 2)
gini = (n_left * gini_left + n_right * gini_right) / (n_left + n_right)
return gini
def predict(self, X):
return np.array([self.predict_sample(x, self.tree) for x in X])
def predict_sample(self, x, tree):
if isinstance(tree, int):
return tree
feature, threshold = tree['feature'], tree['threshold']
if x[feature] < threshold:
return self.predict_sample(x, tree['left'])
else:
return self.predict_sample(x, tree['right'])
```
需要注意的是,上述代码实现的 CART 决策树仅支持分类问题。如果要用于回归问题,需要对 `gini_index` 方法进行修改,使用其他的评估指标(如 MSE)。
相关推荐





