IIS_2023_1/tsyppo_anton_lab_1/main.py

46 lines
2.1 KiB
Python
Raw Normal View History

2023-12-06 14:49:34 +04:00
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Perceptron
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
# Генерируем данные
rs = 42
X, y = make_moons(n_samples=1000, noise=0.3, random_state=rs)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=rs)
def train_and_evaluate_model(model, X_train, y_train, X_test, y_test):
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
return accuracy
# Построение моделей
perceptron_model = Perceptron(random_state=rs)
perceptron_accuracy = train_and_evaluate_model(perceptron_model, X_train, y_train, X_test, y_test)
mlp_model_10_neurons = MLPClassifier(hidden_layer_sizes=(10,), alpha=0.01, random_state=rs)
mlp_10_neurons_accuracy = train_and_evaluate_model(mlp_model_10_neurons, X_train, y_train, X_test, y_test)
mlp_model_100_neurons = MLPClassifier(hidden_layer_sizes=(100,), alpha=0.01, random_state=rs)
mlp_100_neurons_accuracy = train_and_evaluate_model(mlp_model_100_neurons, X_train, y_train, X_test, y_test)
# Построение графиков
plt.figure(figsize=(12, 4))
plt.subplot(131)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='viridis', marker='.')
plt.title("Персептрон\nТочность: {:.2f}%".format(perceptron_accuracy * 100))
plt.subplot(132)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='viridis', marker='.')
plt.title("Многослойный персептрон\nс 10-ю нейронами в скрытом слое\nТочность: {:.2f}%".format(mlp_10_neurons_accuracy * 100))
plt.subplot(133)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='viridis', marker='.')
plt.title("Многослойный персептрон\nс 100-а нейронами в скрытом слое\nТочность: {:.2f}%".format(mlp_100_neurons_accuracy * 100))
plt.tight_layout()
plt.savefig('models.png')
plt.show()