阿信 发表于 2024-6-14 17:55:46

18个机器学习核心算法模型

本帖最后由 阿信 于 2024-6-14 18:04 编辑

在学习机器学习之后,你认为最重要的算法模型有哪些?今儿的内容涉及到
[*]线性回归
[*]逻辑回归
[*]决策树
[*]支持向量机
[*]朴素贝叶斯
[*]K近邻算法
[*]聚类算法
[*]神经网络
[*]集成方法
[*]降维算法
[*]主成分分析
[*]支持向量回归
[*]核方法
[*]最近邻算法
[*]随机森林
[*]梯度提升
[*]AdaBoost
[*]深度学习
我把每种算法模型的核心公式和代码也列举了出来,如果有其他比较重要的算法,大家可以在评论区给出~这20种算法模型,大家可以作为复习,补充对于整个算法的框架。好了,咱们下面对每种算法进行介绍~1. 线性回归(Linear Regression)用于建立自变量(特征)和因变量(目标)之间的线性关系。代码案例from sklearn.linear_model import LinearRegression
import numpy as np

# 创建一些随机数据
X = np.array([, , , ])
y = np.array()

# 拟合模型
model = LinearRegression().fit(X, y)

# 预测
y_pred = model.predict(X)

print("预测值:", y_pred)
2. 逻辑回归(Logistic Regression)用于处理分类问题,通过一个 S 形的函数将输入映射到 0 到 1 之间的概率。
代码案例:from sklearn.linear_model import LogisticRegression
import numpy as np

# 创建一些随机数据
X = np.array([, , , ])
y = np.array()

# 拟合模型
model = LogisticRegression().fit(X, y)

# 预测
y_pred = model.predict(X)

print("预测值:", y_pred)
3. 决策树(Decision Tree)通过一系列决策来学习数据的分类规则或者数值预测规则,可解释性强。代码案例:from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = DecisionTreeClassifier()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)4. 支持向量机(Support Vector Machine,SVM)用于分类和回归分析的监督学习模型,能够在高维空间中构造超平面或超平面集合,实现对数据的有效分类。
代码案例:from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = SVC()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)5. 朴素贝叶斯(Naive Bayes)基于贝叶斯定理和特征条件独立假设的分类算法,常用于文本分类和垃圾邮件过滤。
代码案例:from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = GaussianNB()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)
6. K近邻算法(K-Nearest Nei**ors,KNN)一种基本的分类和回归方法,它的基本假设是“相似的样本具有相似的输出”。代码案例:from sklearn.nei**ors import KNei**orsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = KNei**orsClassifier()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)7. 聚类算法(Clustering)聚类是一种无监督学习方法,将数据集中的样本划分为若干组,使得同一组内的样本相似度较高,不同组之间的样本相似度较低。代码案例:这里以 K 均值聚类为例。from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

# 创建一些随机数据
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)

# 训练模型
model = KMeans(n_clusters=4)
model.fit(X)

# 可视化聚类结果
plt.scatter(X[:, 0], X[:, 1], c=model.labels_, s=50, cmap='viridis')
centers = model.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='red', s=200, alpha=0.5)
plt.show()8. 神经网络(Neural Networks)神经网络是一种模拟人脑神经元网络的计算模型,通过调整神经元之间的连接权重来学习数据的复杂关系。代码案例:这里以使用 TensorFlow 实现一个简单的全连接神经网络为例。import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 创建一些随机数据
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建神经网络模型
model = Sequential([
    Dense(64, activation='relu', input_shape=(20,)),
    Dense(64, activation='relu'),
    Dense(1, activation='sigmoid')
])

# 编译模型
model.compile(optimizer='adam',
            loss='binary_crossentropy',
            metrics=['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))

# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print("准确率:", accuracy)9. 集成方法(Ensemble Methods)集成方法通过组合多个基分类器(或回归器)的预测结果来改善泛化能力和准确性。代码案例:这里以随机森林为例。from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)10. 降维算法(Dimensionality Reduction)降维算法用于减少数据集的维度,保留数据集的重要特征,可以用于数据可视化和提高模型性能。代码案例:from sklearn.decomposition import PCA
from sklearn.datasets import load_iris

# 载入数据
iris = load_iris()
X = iris.data

# 使用 PCA 进行降维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

print("降维后的数据维度:", X_pca.shape)11. 主成分分析(Principal Component Analysis,PCA)主成分分析是一种常用的降维算法,用于发现数据中的主要特征。
代码案例:import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 使用 PCA 进行降维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# 可视化降维结果
plt.figure(figsize=(8, 6))
for i in range(len(np.unique(y))):
plt.scatter(X_pca, X_pca, label=iris.target_names)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.title('PCA of IRIS dataset')
plt.legend()
plt.show()12. 支持向量回归(Support Vector Regression,SVR)SVR 是一种使用支持向量机(SVM)进行回归分析的方法,能够有效处理线性和非线性回归问题。
代码案例:from sklearn.svm import SVR
import numpy as np
import matplotlib.pyplot as plt

# 创建一些随机数据
X = np.sort(5 * np.random.rand(100, 1), axis=0)
y = np.sin(X).ravel()

# 添加噪声
y[::5] += 3 * (0.5 - np.random.rand(20))

# 训练模型
model = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=.1)
model.fit(X, y)

# 预测
X_test = np.linspace(0, 5, 100)[:, np.newaxis]
y_pred = model.predict(X_test)

# 可视化结果
plt.scatter(X, y, color='darkorange', label='data')
plt.plot(X_test, y_pred, color='navy', lw=2, label='prediction')
plt.xlabel('data')
plt.ylabel('target')
plt.title('Support Vector Regression')
plt.legend()
plt.show()
13. 核方法(Kernel Methods)核方法是一种通过在原始特征空间中应用核函数来学习非线性模型的方法,常用于支持向量机等算法。代码案例:from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np

# 创建一些随机数据
X, y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, random_state=42)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义一个高斯核支持向量机模型
model = SVC(kernel='rbf', gamma='scale', random_state=42)

# 训练模型
model.fit(X_train, y_train)

# 可视化决策边界
plt.figure(figsize=(8, 6))
h = .02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = model.predict(np.c_)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title('SVM with RBF Kernel')
plt.show()14. 最近邻算法(K-Nearest Nei**ors,KNN)KNN 是一种基本的分类和回归方法,其基本思想是如果一个样本在特征空间中的 k 个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。代码案例:from sklearn.nei**ors import KNei**orsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = KNei**orsClassifier()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)15. 随机森林(Random Forest)随机森林是一种集成学习方法,通过构建多个决策树来提高分类性能,具有良好的抗过拟合能力和稳定性。
代码案例:from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义一个随机森林模型
model = RandomForestClassifier(n_estimators=100, random_state=42)

# 训练模型
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)16. 梯度提升(Gradient Boosting)梯度提升是一种集成学习方法,通过逐步训练新模型来改善已有模型的预测能力,通常使用决策树作为基础模型。
代码案例:from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)17. AdaBoost(Adaptive Boosting)AdaBoost 是一种集成学习方法,通过串行训练多个弱分类器,并加大误分类样本的权重来提高分类性能。
代码案例:from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 载入数据
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = AdaBoostClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)18. 深度学习(Deep Learning)深度学习是一种基于人工神经网络的机器学习方法,其核心思想是通过多层非线性变换来学习数据的表示。代码案例:这里以使用 TensorFlow 实现一个简单的深度神经网络(多层感知器)为例。import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 创建一些随机数据
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建深度神经网络模型
model = Sequential([
    Dense(64, activation='relu', input_shape=(20,)),
    Dense(64, activation='relu'),
    Dense(1, activation='sigmoid')
])

# 编译模型
model.compile(optimizer='adam',
            loss='binary_crossentropy',
            metrics=['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))

# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print("准确率:", accuracy)

页: [1]
查看完整版本: 18个机器学习核心算法模型