IIS_2023_1/volkov_rafael_lab_1/app.py
2023-12-05 12:27:16 +04:00

61 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import numpy as np
from flask import Flask, request, render_template
from sklearn.datasets import make_circles
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/compare_models', methods=['POST'])
def compare_models():
# Генерация данных
rs = 0
X, y = make_circles(noise=0.2, factor=0.5, random_state=rs)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=rs)
# Персептрон
perceptron = MLPClassifier(hidden_layer_sizes=(1,), max_iter=1000, alpha=0.01)
perceptron.fit(X_train, y_train)
perceptron_score = accuracy_score(y_test, perceptron.predict(X_test))
# Многослойный персептрон с 10-ю нейронами в скрытом слое
mlp_10 = MLPClassifier(hidden_layer_sizes=(10,), max_iter=1000, alpha=0.01)
mlp_10.fit(X_train, y_train)
mlp_10_score = accuracy_score(y_test, mlp_10.predict(X_test))
# Многослойный персептрон со 100-ю нейронами в скрытом слое
mlp_100 = MLPClassifier(hidden_layer_sizes=(100,), max_iter=1000, alpha=0.01)
mlp_100.fit(X_train, y_train)
mlp_100_score = accuracy_score(y_test, mlp_100.predict(X_test))
# Создание графиков
plt.figure(figsize=(12, 4))
plt.subplot(131)
plot_decision_regions(X_test, y_test, clf=perceptron, legend=2)
plt.title('Персептрон\n(Accuracy: {:.2f})'.format(perceptron_score))
plt.subplot(132)
plot_decision_regions(X_test, y_test, clf=mlp_10, legend=2)
plt.title('MLP (10 нейронов)\n(Accuracy: {:.2f})'.format(mlp_10_score))
plt.subplot(133)
plot_decision_regions(X_test, y_test, clf=mlp_100, legend=2)
plt.title('MLP (100 нейронов)\n(Accuracy: {:.2f})'.format(mlp_100_score))
plt.tight_layout()
plt.savefig('static/models_comparison.png')
return render_template('index.html', result=True)
if __name__ == '__main__':
app.run(debug=True)