Advertisement
fevzi02

Untitled

Dec 26th, 2023
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn.tree import DecisionTreeClassifier
  4. from sklearn.datasets import load_iris
  5. from sklearn.model_selection import train_test_split
  6. from matplotlib.colors import ListedColormap
  7.  
  8. # Загрузка датасета ириса Фишера
  9. iris = load_iris()
  10. X = iris.data[:, [2, 3]] # используем только два признака для визуализации
  11. y = iris.target
  12.  
  13. # Разделение данных на обучающую и тестовую выборки
  14. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
  15.  
  16. # Обучение модели решающего дерева
  17. tree_model = DecisionTreeClassifier(max_depth=3)
  18. tree_model.fit(X_train, y_train)
  19.  
  20. # Визуализация границ решения
  21. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
  22. y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
  23. xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
  24. np.arange(y_min, y_max, 0.01))
  25.  
  26. Z = tree_model.predict(np.c_[xx.ravel(), yy.ravel()])
  27. Z = Z.reshape(xx.shape)
  28.  
  29. # Создание цветовой карты
  30. cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
  31. cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
  32.  
  33. # Визуализация результата
  34. plt.figure(figsize=(10, 6))
  35. plt.contourf(xx, yy, Z, alpha=0.4, cmap=cmap_light)
  36. plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, edgecolor='k', s=20)
  37. plt.xlim(xx.min(), xx.max())
  38. plt.ylim(yy.min(), yy.max())
  39. plt.title("Классификация ирисов с помощью решающего дерева")
  40. plt.xlabel(iris.feature_names[2])
  41. plt.ylabel(iris.feature_names[3])
  42.  
  43. plt.show()
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement