【python代码实现】决策树分类算法、朴素贝叶斯分类算法以及人工神经网络分类算法的代码及数据
时间: 2023-07-05 15:09:27 浏览: 93
手工实现KNN和朴素贝叶斯算法对鸢尾花数据进行自动分类 完整代码+数据 可直接运行
5星 · 资源好评率100%
以下是三种分类算法的Python实现和数据:
决策树分类算法:
```
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载iris数据集
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=42)
# 构建决策树模型
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
# 预测并计算准确率
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
朴素贝叶斯分类算法:
```
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载iris数据集
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=42)
# 构建朴素贝叶斯模型
clf = GaussianNB()
clf.fit(X_train, y_train)
# 预测并计算准确率
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
人工神经网络分类算法:
```
from sklearn import datasets
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载iris数据集
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=42)
# 构建人工神经网络模型
clf = MLPClassifier(hidden_layer_sizes=(5, 2), max_iter=1000)
clf.fit(X_train, y_train)
# 预测并计算准确率
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
iris数据集可以通过`datasets.load_iris()`方法加载,也可以从网站下载。
阅读全文