likes
comments
collection
share

机器学习之监督学习和无监督学习

作者站长头像
站长
· 阅读数 4

监督学习和无监督学习是机器学习中两种常见的学习方法。监督学习是指在给定输入和相应的输出标签(即已知答案)的情况下,通过训练模型来预测未知的输入标签。无监督学习则是在没有标签的情况下,根据数据内在的特点进行模式识别和分类。

监督学习

监督学习中最基本的算法是线性回归和逻辑回归。其中,线性回归适用于预测连续的输出,例如预测房价、股票价格等;逻辑回归适用于预测二元分类输出,例如判断一封电子邮件是否是垃圾邮件等。

下面以线性回归为例,介绍监督学习的基本流程。

首先,我们需要定义模型的参数和损失函数。在线性回归中,模型的参数是一个系数矩阵W和一个偏置项b,损失函数通常选用均方误差(MSE)。

import numpy as np

class LinearRegression:
    def __init__(self, lr=0.01, n_iters=1000):
        self.lr = lr
        self.n_iters = n_iters
        self.W = None
        self.b = None

    def fit(self, X, y):
        n_samples, n_features = X.shape
        self.W = np.zeros(n_features)
        self.b = 0

        for i in range(self.n_iters):
            y_pred = np.dot(X, self.W) + self.b
            dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
            db = (1/n_samples) * np.sum(y_pred - y)
            self.W -= self.lr * dw
            self.b -= self.lr * db

    def predict(self, X):
        y_pred = np.dot(X, self.W) + self.b
        return y_pred

接下来,我们需要准备数据并进行训练。在这个例子中,我们使用一个简单的数据集,包含两个特征和一个目标变量。

X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
y = np.array([3, 5, 7, 9, 11])

model = LinearRegression(lr=0.05, n_iters=1000)
model.fit(X, y)
y_pred = model.predict(X)

print(y_pred)

最后,我们可以使用模型进行预测。在这个例子中,我们使用训练集作为测试集,输出预测结果。

>>> [2.94550504  4.94236249  6.93921994  8.9360774  10.93293485]

2.1 聚类

聚类是一种将数据分成不同组的方法,每一组被称为一个簇。聚类的目标是使同一个簇内的数据点尽可能相似,而不同簇之间的数据点差异较大。

其中最常见的聚类算法是K-Means算法。该算法的主要思想是随机选择K个数据点作为初始质心,然后将每个数据点分配给离它最近的质心所在的簇。接下来,重新计算每个簇的质心,并重复以上步骤,直到质心不再改变或达到最大迭代次数为止。

下面是一个简单的K-Means实现:

import numpy as np
from sklearn.datasets import make_blobs
from matplotlib import pyplot as plt

class KMeans:
    def __init__(self, n_clusters=3, max_iter=100):
        self.n_clusters = n_clusters
        self.max_iter = max_iter
        self.centroids = None

    def fit(self, X):
        n_samples, n_features = X.shape
        self.centroids = np.random.randn(self.n_clusters, n_features)

        for i in range(self.max_iter):
            distances = np.zeros((n_samples, self.n_clusters))

            for j in range(self.n_clusters):
                distances[:, j] = np.linalg.norm(X - self.centroids[j], axis=1)

            cluster_labels = np.argmin(distances, axis=1)

            for j in range(self.n_clusters):
                self.centroids[j] = np.mean(X[cluster_labels == j], axis=0)

    def predict(self, X):
        distances = np.zeros((X.shape[0], self.n_clusters))

        for j in range(self.n_clusters):
            distances[:, j] = np.linalg.norm(X - self.centroids[j], axis=1)

        cluster_labels = np.argmin(distances, axis=1)
        return cluster_labels

# 生成随机数据
X, y = make_blobs(n_samples=300, centers=3, cluster_std=0.8, random_state=0)

# 训练模型并预测簇标签
kmeans = KMeans(n_clusters=3, max_iter=100)
kmeans.fit(X)
y_pred = kmeans.predict(X)

# 可视化结果
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='x', color='r', s=100)
plt.show()

2.2 降维

降维是将高维数据转换为低维数据的过程,常用于数据可视化和特征提取。其中最常见的降维算法是主成分分析(PCA)。

PCA的主要思想是将数据投影到一个新的坐标系中,使得投影后的数据方差最大。在PCA中,我们首先计算数据的协方差矩阵,然后通过对协方差矩阵进行特征值分解来获取新坐标系的基向量,最后将数据投影到新的坐标系中。

下面是一个简单的PCA实现:

import numpy as np

class PCA:
    def __init__(self, n_components):
        self.n_components = n_components
        self.components = None

    def fit(self, X):
        # 计算协方差矩阵
        X_mean = np.mean(X, axis=0)
        X_centered = X - X_mean
        cov_matrix = np.cov(X_centered, rowvar=False)

        # 对协方差矩阵进行特征值分解
        eigenvalues, eigenvectors = np.linalg.eigh(cov_matrix)

        # 获取新坐标系的基向量
        self.components = eigenvectors[:, ::-1][:, :self.n_components]

    def transform(self, X):
        # 将数据投影到新坐标系中
        X_centered = X - np.mean(X, axis=0)
        return np.dot(X_centered, self.components)

# 生成随机数据
X = np.random.randn(100, 3)

# 进行PCA降维
pca = PCA(n_components=2)
pca.fit(X)
X_transformed = pca.transform(X)

# 可视化结果
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2])
plt.figure()
plt.scatter(X_transformed[:, 0], X_transformed[:, 1])
plt.show()

总结

监督学习和无监督学习是机器学习中两个最基本的学习范式。监督学习通过训练数据集中的标签信息来建立输入和输出之间的映射关系,常用于分类和回归问题。常见的监督学习算法包括线性回归、逻辑回归、决策树、SVM和神经网络等。

无监督学习则不依赖于标签信息,通过对数据进行聚类、降维等操作来发现数据内在的结构和模式。常见的无监督学习算法包括K-Means聚类和主成分分析(PCA)降维等。