1. 引言
Scikit-learn是一个强大的Python机器学习库,它提供了丰富的算法和工具来处理数据分析和建模。可视化是机器学习过程中的一个重要环节,它可以帮助我们更好地理解数据、模型和结果。本篇文章将提供50个实用的Scikit-learn可视化代码示例,帮助您轻松入门并掌握这一技能。
2. 数据可视化基础
在开始具体的代码示例之前,我们需要了解一些数据可视化的基础知识。
2.1. Matplotlib库
Matplotlib是Python中最常用的绘图库之一,它提供了丰富的绘图功能,可以生成各种类型的图表。
2.2. Seaborn库
Seaborn是基于Matplotlib的另一个绘图库,它提供了更高级的绘图功能,使得绘制复杂图表变得更加容易。
2.3. Scikit-learn可视化工具
Scikit-learn本身也提供了一些可视化工具,如plot_decision_regions和plot_confusion_matrix等。
3. 代码示例
3.1. 简单散点图
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.random.rand(50)
y = np.random.rand(50)
# 绘制散点图
plt.scatter(x, y)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('简单散点图')
plt.show()
3.2. 直方图
# 创建数据
data = np.random.randn(1000)
# 绘制直方图
plt.hist(data, bins=30)
plt.xlabel('值')
plt.ylabel('频数')
plt.title('直方图')
plt.show()
3.3. 箱线图
import seaborn as sns
# 创建数据
data = np.random.randn(1000)
# 绘制箱线图
sns.boxplot(data=data)
plt.title('箱线图')
plt.show()
3.4. 决策边界图
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# 创建数据
X, y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建模型
model = LogisticRegression()
# 训练模型
model.fit(X_train, y_train)
# 绘制决策边界
plt.figure(figsize=(8, 6))
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=plt.cm.Paired, edgecolors='k')
plt.xlabel('特征1')
plt.ylabel('特征2')
plt.title('决策边界图')
plt.show()
3.5. 混淆矩阵
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# 加载数据
data = load_iris()
X = data.data
y = data.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建模型
model = LogisticRegression()
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 绘制混淆矩阵
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('预测值')
plt.ylabel('真实值')
plt.title('混淆矩阵')
plt.show()
4. 总结
通过以上50个实用的Scikit-learn可视化代码示例,您应该能够掌握基本的数据可视化技能。这些示例涵盖了从简单散点图到复杂混淆矩阵的各种图表类型。在实际应用中,您可以根据需要选择合适的图表来展示您的数据和分析结果。
