import numpy as np from flask import Flask, request, render_template from sklearn.datasets import make_moons from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt 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_moons(noise=0.3, random_state=rs) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=rs) # Линейная регрессия lr = LinearRegression() lr.fit(X_train, y_train) lr_score = lr.score(X_test, y_test) # Полиномиальная регрессия (степень 3) poly = PolynomialFeatures(degree=3) X_poly = poly.fit_transform(X_train) poly_reg = LinearRegression() poly_reg.fit(X_poly, y_train) poly_score = poly_reg.score(poly.transform(X_test), y_test) # Гребневая полиномиальная регрессия (степень 3, alpha=1.0) ridge = Ridge(alpha=1.0) ridge.fit(X_poly, y_train) ridge_score = ridge.score(poly.transform(X_test), y_test) # Создание графиков plt.figure(figsize=(12, 4)) plt.subplot(131) plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.RdBu) plt.title('Линейная регрессия\n(Score: {:.2f})'.format(lr_score)) plt.subplot(132) plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.RdBu) plt.title('Полиномиальная регрессия\n(Score: {:.2f})'.format(poly_score)) plt.subplot(133) plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.RdBu) plt.title('Гребневая полиномиальная регрессия\n(Score: {:.2f})'.format(ridge_score)) plt.tight_layout() plt.savefig('static/models_comparison.png') return render_template('index.html', result=True) if __name__ == '__main__': app.run(debug=True)