首先,加载这些数据集。
from sklearn.datasets import load_winefrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegression, LinearRegressionfrom sklearn.svm import SVCfrom sklearn.neural_network import MLPClassifierfrom sklearn.metrics import accuracy_score, r2_scoreimport pandas as pdimport matplotlib.pyplot as plt接下来,让加载葡萄酒数据集并使其准备好构建那些模型。最后,您将看到这些算法可以逐个应用,并将评估指标添加到数据框中,以便在最后进行比较。
# Load the wine datasetwine = load_wine()X_wine = wine.datay_wine_quality = wine.target # For classification# For simplicity in regression, let's predict the total phenols (a continuous feature) from the wine dataset# This is just for demonstration and not a standard practiceX_wine_regression = StandardScaler().fit_transform(X_wine) # Standardize for neural network efficiencyy_wine_phenols = X_wine[:, wine.feature_names.index('total_phenols')] # Selecting a continuous feature# Split the dataset for classificationX_train_class, X_test_class, y_train_class, y_test_class = train_test_split(X_wine, y_wine_quality, test_size=0.2, random_state=42)# Split the dataset for regressionX_train_reg, X_test_reg, y_train_reg, y_test_reg = train_test_split(X_wine_regression, y_wine_phenols, test_size=0.2, random_state=42)# Reinitialize models to reset any previous traininglogistic_model = LogisticRegression(max_iter=200)svm_model = SVC(probability=True)neural_network_model = MLPClassifier(max_iter=2000)linear_regression_model = LinearRegression()# Train and evaluate models for classificationlogistic_model.fit(X_train_class, y_train_class)logistic_pred_class = logistic_model.predict(X_test_class)logistic_accuracy = accuracy_score(y_test_class, logistic_pred_class)svm_model.fit(X_train_class, y_train_class)svm_pred_class = svm_model.predict(X_test_class)svm_accuracy = accuracy_score(y_test_class, svm_pred_class)neural_network_model.fit(X_train_class, y_train_class)neural_network_pred_class = neural_network_model.predict(X_test_class)neural_network_accuracy = accuracy_score(y_test_class, neural_network_pred_class)# Train and evaluate Linear Regression for regressionlinear_regression_model.fit(X_train_reg, y_train_reg)linear_regression_pred_reg = linear_regression_model.predict(X_test_reg)linear_regression_r2 = r2_score(y_test_reg, linear_regression_pred_reg)# Store results in a DataFrameresults_df_wine = pd.DataFrame({ 'Model': ['Logistic Regression (Class)', 'SVM (Class)', 'Neural Network (Class)', 'Linear Regression (Reg)'], 'Accuracy/R²': [logistic_accuracy, svm_accuracy, neural_network_accuracy, linear_regression_r2]})# Display the DataFrameresults_df_wine这里是输出。
[attach]854492[/attach]
现在,让这个输出看起来更好。
# Plotting results for the Wine datasetplt.figure(figsize=(10, 6))plt.barh(results_df_wine['Model'], results_df_wine['Accuracy/R²'], color=['blue', 'orange', 'green', 'red'])plt.xlabel('Score')plt.title('Model Evaluation on Wine Dataset (Classification & Regression)')plt.xlim(0, 1.1) # Extend x-axis a bit for clarityfor index, value in enumerate(results_df_wine['Accuracy/R²']): plt.text(value, index, f"{value:.2f}", va='center')plt.savefig("supervised.png")plt.show()这里是输出。