鸢尾花的分类和聚类算法代码实现
时间: 2023-07-12 20:42:39 浏览: 86
好的,以下是鸢尾花分类和聚类算法的代码实现:
1. 鸢尾花分类(Python代码)
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载数据
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
# 测试模型
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
2. 鸢尾花聚类(Python代码)
```python
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# 加载数据
iris = load_iris()
X, y = iris.data, iris.target
# 计算轮廓系数
scores = []
for k in range(2, 11):
kmeans = KMeans(n_clusters=k, random_state=42)
kmeans.fit(X)
score = silhouette_score(X, kmeans.labels_)
scores.append(score)
# 找到最优的K
best_k = scores.index(max(scores)) + 2
# 训练模型
kmeans = KMeans(n_clusters=best_k, random_state=42)
kmeans.fit(X)
# 输出聚类结果
print("Cluster labels:", kmeans.labels_)
```
希望能够帮助到你!
阅读全文