Home >Backend Development >Python Tutorial >Supervised vs. Unsupervised Learning
Machine learning (ML) is a powerful tool that enables computers to learn from data and make predictions or decisions. But not all machine learning is the same – there are different types of learning, each suitable for specific tasks. The two most common types are supervised learning and unsupervised learning. In this article, we'll explore the differences between them, provide real-world examples, and walk through code snippets to help you understand how they work.
Supervised learning is a type of machine learning in which an algorithm learns from labeled data. In other words, the data you provide to the model includes input features and the correct outputs (labels). The goal is for the model to learn the relationship between inputs and outputs so that it can make accurate predictions on new, unseen data.
Email Spam Detection:
House Price Forecast:
Medical Diagnosis:
Unsupervised learning is a type of machine learning in which algorithms learn from unlabeled data. Unlike supervised learning, no correct output is provided. Instead, models try to find patterns, structures, or relationships in the data on their own.
Customer segmentation:
Anomaly detection:
Market Basket Analysis:
**方面** | **监督学习** | **无监督学习** |
---|---|---|
**数据** | 标记的(提供输入和输出) | 未标记的(仅提供输入) |
**目标** | 预测结果或对数据进行分类 | 发现数据中的模式或结构 |
**示例** | 分类、回归 | 聚类、降维 |
**复杂性** | 更容易评估(已知输出) | 更难评估(没有基本事实) |
**用例** | 垃圾邮件检测、价格预测 | 客户细分、异常检测 |
Let’s dig into some code and see how supervised and unsupervised learning work in practice. We will use Python and the popular Scikit-learn library.
We will use a simple linear regression model to predict the price of a home based on characteristics such as square footage.
<code class="language-python"># 导入库 import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # 创建样本数据集 data = { 'SquareFootage': [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700], 'Price': [245000, 312000, 279000, 308000, 199000, 219000, 405000, 324000, 319000, 255000] } df = pd.DataFrame(data) # 特征 (X) 和标签 (y) X = df[['SquareFootage']] y = df['Price'] # 将数据分成训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 训练线性回归模型 model = LinearRegression() model.fit(X_train, y_train) # 做出预测 y_pred = model.predict(X_test) # 评估模型 mse = mean_squared_error(y_test, y_pred) print(f"均方误差:{mse:.2f}")</code>
We will use K-means clustering algorithm to group customers based on their age and spending habits.
<code class="language-python"># 导入库 import numpy as np import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt # 创建样本数据集 data = { 'Age': [25, 34, 22, 45, 32, 38, 41, 29, 35, 27], 'SpendingScore': [30, 85, 20, 90, 50, 75, 80, 40, 60, 55] } df = pd.DataFrame(data) # 特征 (X) X = df[['Age', 'SpendingScore']] # 训练 K 均值聚类模型 kmeans = KMeans(n_clusters=3, random_state=42) df['Cluster'] = kmeans.fit_predict(X) # 可视化集群 plt.scatter(df['Age'], df['SpendingScore'], c=df['Cluster'], cmap='viridis') plt.xlabel('年龄') plt.ylabel('消费评分') plt.title('客户细分') plt.show()</code>
Supervised learning and unsupervised learning are two basic methods in machine learning, each with its own advantages and use cases. Supervised learning is great for making predictions when you have labeled data, while unsupervised learning is great when you want to explore and discover patterns in unlabeled data.
By understanding the differences and practicing with real-world examples, such as the ones in this article, you will master these basic machine learning techniques. If you have any questions or want to share your own experiences, please feel free to leave a comment below.
The above is the detailed content of Supervised vs. Unsupervised Learning. For more information, please follow other related articles on the PHP Chinese website!