智客公社

标题: 机器学习各种类型和应用的理解指南 [打印本页]

作者: 周杰伦是大帅哥    时间: 2025-2-27 08:07
标题: 机器学习各种类型和应用的理解指南
[attach]854490[/attach]

机器学习分为监督学习、无监督学习和强化学习
监督学习

机器学习,称为监督学习,使用标记数据来训练模型。它就像用例子教学。输入和正确的输出在训练数据中相结合。
关键应用和示例


[attach]854491[/attach]

优势

监督学习模型具有足够的训练数据下进行准确预测的预测能力,并且其结果通常易于理解和解释。
局限性

监督学习的一个显著挑战是它需要大量的标记数据,这可能很昂贵、耗时,有时还难以收集。
此外,存在过拟合的风险,即模型在训练数据上表现良好,但在未见过的数据上表现较差。
流行算法

现在,让我们看看流行的算法及其简单解释。
监督学习算法的应用

首先,加载这些数据集。
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()这里是输出。

[attach]854493[/attach]

现在,让我评估结果。
无监督学习

无监督学习涉及使用没有标记响应的数据来训练模型。这意味着你想要预测的示例数据在数据集中不存在。使用这种方法,算法试图在不给出特定预测的情况下学习数据结构。它通过降低数据的维度,并根据相似性和差异性将数据点分组为簇来发现模式。
关键应用和示例:


[attach]854494[/attach]

优势

无监督学习可以在没有标签的情况下发现数据中的隐藏模式,这使得它在探索性数据分析中非常有用。当不确定数据中需要什么时,它尤其有价值。
局限性

然而,缺乏标记数据使得验证模型性能具有挑战性。此外,解释无监督学习算法的结果可能比监督学习更复杂和主观。
流行算法

应用无监督学习

现在看看代码。我们首先加载库。
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 = StandardScaler()X_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这里是输出。

[attach]854495[/attach]

强化学习

强化学习(RL)是一种机器学习类型,其中智能体通过在环境中采取行动以实现某些目标来学习做出决策。
与用奖励和惩罚训练宠物类似:代理学习在时间上最大化奖励的最佳行为。
在强化学习中,智能体与其环境交互,通过奖励或惩罚获得反馈,并调整其策略以提高未来的奖励。学习过程包括探索(尝试新事物)和利用(使用已知信息获得奖励)。
关键应用和示例


[attach]854496[/attach]

优势

强化学习对于涉及一系列判断的任务非常强大。它允许模型从行动的结果中学习,这对于难以表达精确指令的复杂问题很有帮助。
局限性

然而,强化学习需要大量的数据和计算能力才能成功学习。在没有意外结果的情况下,可能很难创建一个理想的直接学习奖励系统。
流行算法

其他机器学习类型

这些方法通过利用不同的数据配置和隐私考虑,扩展了机器学习模型的能力,为应用和效率提升开辟了新的可能性。
如何选择适合不同任务和项目的机器学习类型?

选择合适的机器学习类型取决于多个因素,包括数据性质、当前任务以及可用资源。以下是一些考虑因素:
理解您项目的具体需求和限制是选择最合适的机器学习方法的关键。这一决策将影响您解决方案的有效性、效率和可扩展性。
最后思考

因此,我们已对机器学习进行了相当深入的探索,从不同类型机器学习的清晰水域到深水区,我们都涉猎了。
编码这些机器学习算法的关键不仅在于理解它们,还在于卷起袖子,通过实际项目(如DoorDash 项目)亲自动手,目的是预测配送时长。
作者: 又月巴又月半    时间: 2025-2-27 22:14
呵呵,低调,低调!
作者: heromxs    时间: 2025-3-1 13:05
站位支持
作者: Lx纸巾    时间: 2025-3-1 13:05
LZ帖子不给力,勉强给回复下吧




欢迎光临 智客公社 (https://bbs.cnaiplus.com/) Powered by Discuz! X3.5