摘要:from sklearn.datasets import load_winefrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_te
机器学习分为监督学习、无监督学习和强化学习
机器学习,称为监督学习,使用标记数据来训练模型。它就像用例子教学。输入和正确的输出在训练数据中相结合。
监督学习模型具有足够的训练数据下进行准确预测的预测能力,并且其结果通常易于理解和解释。
监督学习的一个显著挑战是它需要大量的标记数据,这可能很昂贵、耗时,有时还难以收集。
此外,存在过拟合的风险,即模型在训练数据上表现良好,但在未见过的数据上表现较差。
现在,让我们看看流行的算法及其简单解释。
线性回归:预测连续输出。逻辑回归:用于二元分类任务。支持向量机(SVM):找到不同类别数据点之间的最佳边界。神经网络:可以使用神经元层来模拟复杂模式。首先,加载这些数据集。
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_wineX_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这里是输出。
现在,让这个输出看起来更好。
# 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这里是输出。
现在,让我评估结果。
强:逻辑回归:在分类任务中表现出色,准确率达到 97%,表明数据集模式拟合良好。SVM: 在 81%时显示较低的准确率,表明可能存在欠拟合或需要调整参数和优化核选择。神经网络:达到与逻辑回归相似的高精度,反映了其建模数据集中复杂关系的能力。线性回归:报告了一个不切实际的完美 R²分数,暗示了过于乐观的拟合,需要进一步审查以确定潜在的数据泄露或过拟合。无监督学习涉及使用没有标记响应的数据来训练模型。这意味着你想要预测的示例数据在数据集中不存在。使用这种方法,算法试图在不给出特定预测的情况下学习数据结构。它通过降低数据的维度,并根据相似性和差异性将数据点分组为簇来发现模式。
关键应用和示例:无监督学习可以在没有标签的情况下发现数据中的隐藏模式,这使得它在探索性数据分析中非常有用。当不确定数据中需要什么时,它尤其有价值。
局限性然而,缺乏标记数据使得验证模型性能具有挑战性。此外,解释无监督学习算法的结果可能比监督学习更复杂和主观。
流行算法K-means 聚类:根据特征相似性将数据分组为 k 个簇。层次聚类:通过不断合并或拆分现有聚类来构建一个聚类树。主成分分析(PCA):在保留大部分变化的同时降低数据的维度。自编码器:设计用于将数据压缩到低维表示,然后重建它的神经网络。应用无监督学习现在看看代码。我们首先加载库。
from sklearn.cluster import kmeans, AgglomerativeClusteringfrom sklearn.metrics import silhouette_scorefrom sklearn.decomposition import PCAfrom sklearn.neural_network import MLPRegressor接下来,让标准化数据,应用这些算法,并将结果添加到字典中。我们将在最后进行比较。
# Standardize the data for clustering and autoencoderscaler = StandardScalerX_scaled = scaler.fit_transform(X_wine)# Apply K-means Clusteringkmeans = KMeans(n_clusters=3, random_state=42) # We choose 3 as a starting point, as there are 3 classes of winekmeans.fit(X_scaled)kmeans_labels = kmeans.labels_kmeans_silhouette = silhouette_score(X_scaled, kmeans_labels)# Apply Hierarchical Clusteringhierarchical = AgglomerativeClustering(n_clusters=3) # Same number of clusters for comparisonhierarchical.fit(X_scaled)hierarchical_labels = hierarchical.labels_hierarchical_silhouette = silhouette_score(X_scaled, hierarchical_labels)# Apply PCApca = PCA(n_components=0.95) # Retain 95% of the varianceX_pca = pca.fit_transform(X_scaled)pca_explained_variance = pca.explained_variance_ratio_.sum# Train an Autoencoder - For simplicity, we'll design a small oneautoencoder = MLPRegressor(hidden_layer_sizes=(32, 16, 32), max_iter=2000, random_state=42)autoencoder.fit(X_scaled, X_scaled)X_reconstructed = autoencoder.predict(X_scaled)autoencoder_reconstruction_error = ((X_scaled - X_reconstructed) ** 2).mean# Compile the resultsunsupervised_results = { 'K-means Clustering': kmeans_silhouette, 'Hierarchical Clustering': hierarchical_silhouette, 'PCA Explained Variance': pca_explained_variance, 'Autoencoder Reconstruction Error': autoencoder_reconstruction_error}unsupervised_results这里是输出。
强化学习(RL)是一种机器学习类型,其中智能体通过在环境中采取行动以实现某些目标来学习做出决策。
与用奖励和惩罚训练宠物类似:代理学习在时间上最大化奖励的最佳行为。
在强化学习中,智能体与其环境交互,通过奖励或惩罚获得反馈,并调整其策略以提高未来的奖励。学习过程包括探索(尝试新事物)和利用(使用已知信息获得奖励)。
关键应用和示例强化学习对于涉及一系列判断的任务非常强大。它允许模型从行动的结果中学习,这对于难以表达精确指令的复杂问题很有帮助。
局限性然而,强化学习需要大量的数据和计算能力才能成功学习。在没有意外结果的情况下,可能很难创建一个理想的直接学习奖励系统。
流行算法半监督学习是一种混合方法,它使用标记和无标记数据来训练。当获取完整标记的数据集成本高昂或不切实际时,这种方法很有用。这种方法可以在较少的标记数据下提高学习精度。自监督学习是一种无监督学习形式,其中数据提供监督。系统通过预训练任务学习从输入的其他部分预测输入的一部分。它在标签数据稀缺但未标记数据丰富的场景中特别有效。联邦学习是一种机器学习方法,它在不交换数据的情况下,在多个持有本地数据样本的分布式设备或服务器上训练算法。这种方法有利于保护隐私和数据安全,并减少了集中化大量数据集的需求。这些方法通过利用不同的数据配置和隐私考虑,扩展了机器学习模型的能力,为应用和效率提升开辟了新的可能性。
选择合适的机器学习类型取决于多个因素,包括数据性质、当前任务以及可用资源。以下是一些考虑因素:
数据可用性和标注:如果您有一个大量标注的数据集,监督学习通常是最佳选择。对于未标注数据,考虑无监督学习。当您有有限的标注数据时,半监督学习或自监督学习可能非常强大。任务复杂度和要求:强化学习适用于需要随时间进行决策的任务,如机器人或游戏。对于分类或回归任务,监督学习算法更为合适。隐私担忧:如果数据隐私是担忧的问题,联邦学习允许在去中心化数据上进行训练,保护用户隐私。计算资源:强化学习和深度学习模型可能需要大量的计算资源。确保您的选择与可用的计算预算相匹配。特定领域考虑:一些领域,如生物信息学或金融,可能具有特定的要求或普遍的做法,这些做法有利于某些类型的机器学习。理解您项目的具体需求和限制是选择最合适的机器学习方法的关键。这一决策将影响您解决方案的有效性、效率和可扩展性。
因此,我们已对机器学习进行了相当深入的探索,从不同类型机器学习的清晰水域到深水区,我们都涉猎了。
编码这些机器学习算法的关键不仅在于理解它们,还在于卷起袖子,通过实际项目(如DoorDash 项目)亲自动手,目的是预测配送时长。
来源:自由坦荡的湖泊AI