一、ROC曲线(ROC Curve for Model Performance)

用于评价二分类模型的性能。

import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np

# 示例数据
y_true = np.random.randint(0, 2, 100)
y_scores = np.random.rand(100)

# 计算ROC曲线
fpr, tpr, _ = roc_curve(y_true, y_scores)
roc_auc = auc(fpr, tpr)

# 绘制ROC曲线
plt.plot(fpr, tpr, label='AUC = %0.2f' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend(loc='lower right')
plt.show()

1763012478710-70a4c153-95e3-4212-9db0-8c5bf071bf33

二、精确率-召回率曲线(Precision-Recall Curve)

用于评价二分类模型的性能。

import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve

# 示例数据
y_true = np.random.randint(0, 2, 100)
y_scores = np.random.rand(100)

# 计算精确率-召回率曲线
precision, recall, _ = precision_recall_curve(y_true, y_scores)

# 绘制精确率-召回率曲线
plt.plot(recall, precision)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.show()

1763012478775-b0b15967-0fc5-4d89-bf97-0e8575f4d73d

三、混淆矩阵(Confusion Matrix)

用于展示分类模型的性能。

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns
import numpy as np

# 示例数据
y_true = np.random.randint(0, 3, 100)
y_pred = np.random.randint(0, 3, 100)

# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)

# 绘制混淆矩阵
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Confusion Matrix')
plt.show()

1763012478849-1b109041-e26b-4f52-8d78-4a8287969b3e

四、残差图(Residual Plot)

用于回归分析中查看模型残差。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.linear_model import LinearRegression

# 生成示例数据
np.random.seed(42)
x = np.random.rand(100, 1) * 10
y = 2 * x + 1 + np.random.randn(100, 1) * 2
# 拟合线性回归模型
model = LinearRegression()
model.fit(x, y)
y_pred = model.predict(x)

# 计算残差
residuals = y - y_pred

# 创建图形
plt.figure(figsize=(10, 6))

# 绘制残差图
sns.scatterplot(x=y_pred.flatten(), y=residuals.flatten(), alpha=0.7, s=60, color='blue', edgecolor='w')

# 添加辅助线
plt.axhline(0, color='red', linestyle='--', linewidth=2)
plt.axhline(np.mean(residuals), color='green', linestyle='--', linewidth=2)
plt.axhline(np.mean(residuals) + np.std(residuals), color='purple', linestyle='--', linewidth=1)
plt.axhline(np.mean(residuals) - np.std(residuals), color='purple', linestyle='--', linewidth=1)

# 设置标签和标题
plt.xlabel('Predicted Values')
plt.ylabel('Residuals')
plt.title('Residual Plot')
plt.grid(True)

# 显示图形
plt.show()

1763012478906-739b2fc0-d00b-46fa-a1dc-bc0f9c27e2aa

五、聚类结果可视化(Clustering Plot)

用于显示聚类结果。

import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import seaborn as sns
import numpy as np

# 示例数据
X = np.random.rand(100, 2)

# 训练模型
kmeans = KMeans(n_clusters=3).fit(X)
labels = kmeans.labels_

# 绘制聚类结果
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=labels, palette='viridis')
plt.title('Clustering Plot')
plt.show()

1763012478963-086cf01e-6f2b-4872-8a34-ed342338a2ec

六、累积解释变量重要性(Cumulative Feature Importance)

用于显示特征重要性的累积贡献。

import matplotlib.pyplot as plt
import numpy as np

# 示例数据
features = ['Feature1', 'Feature2', 'Feature3', 'Feature4']
importance = np.array([0.4, 0.3, 0.2, 0.1])
cumulative_importance = np.cumsum(importance)

# 绘制累积特征重要性
plt.plot(features, cumulative_importance, marker='o')
plt.xlabel('Feature')
plt.ylabel('Cumulative Importance')
plt.title('Cumulative Feature Importance')
plt.show()

1763012479022-5280fccb-40e1-4524-8b79-61aac3cb0d11

七、约束可视化(Constraint Visualization)

用于显示约束条件的可行域()

import matplotlib.pyplot as plt
import numpy as np

# 示例约束条件
x = np.linspace(0, 5, 400)
y1 = 5 - x
y2 = x

# 绘制约束条件
plt.plot(x, y1, label='Constraint 1: y <= 5 - x')
plt.plot(x, y2, label='Constraint 2: y >= x')
plt.fill_between(x, np.maximum(y1, y2), 5, color='gray', alpha=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Constraint Visualization')
plt.legend()
plt.show()

1763012479084-727a50f1-b319-4e3b-8d5f-4ae6699ff12f

八、参数空间探索(Parameter Space Exploration)

用于显示不同参数组合下目标函数的值。

import matplotlib.pyplot as plt
import numpy as np

# 示例目标函数
def objective_function(x, y):
return np.sin(x) + np.cos(y)

# 示例数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = objective_function(X, Y)

# 绘制参数空间探索图
plt.contourf(X, Y, Z, 20, cmap='viridis')
plt.colorbar()
plt.xlabel('Parameter 1')
plt.ylabel('Parameter 2')
plt.title('Parameter Space Exploration')
plt.show()

1763012479146-2464bc72-1177-418d-8c89-c57a742fd16a

九、优化路径图(Optimization Path)

用于显示优化过程中的搜索路径。

import matplotlib.pyplot as plt
import numpy as np

# 示例目标函数
def objective_function(x, y):
return x**2 + y**2

# 优化路径示例数据
path_x = np.array([0, 1, 2, 1, 0.5, 0.1, 0])
path_y = np.array([0, 0.5, 1, 1.5, 1.2, 0.8, 0.2])

# 绘制优化路径图
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = objective_function(X, Y)

plt.contour(X, Y, Z, levels=20)
plt.plot(path_x, path_y, marker='o', color='r')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Optimization Path')
plt.show()

1763012479205-62caab7b-74c0-42da-bb9d-21b5c3b337be

十、多峰三维图

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# 示例数据
np.random.seed(0)
objectives = np.random.rand(100, 3) # 生成随机数据
pareto_front = objectives[np.lexsort((objectives[:, 0], objectives[:, 1], objectives[:, 2]))]


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(pareto_front[:, 0], pareto_front[:, 1], pareto_front[:, 2], cmap='viridis')

# 标题和标签
ax.set_title('3D')
ax.set_xlabel('Objective 1')
ax.set_ylabel('Objective 2')
ax.set_zlabel('Objective 3')

plt.show()

1763012479281-ad4ca76c-fd54-4221-96ed-5328cb3b4fe4

十一、动态系统稳定性(Dynamic System Stability)

用于显示动态系统的稳定性。

import matplotlib.pyplot as plt
import numpy as np

# 示例数据
time = np.linspace(0, 10, 100)
state = np.exp(-0.5 * time) * np.cos(2 * time)

# 绘制动态系统稳定性图
plt.plot(time, state)
plt.xlabel('Time')
plt.ylabel('State')
plt.title('Dynamic System Stability')
plt.show()

1763012479347-0e557a98-49fa-4dc1-adec-384985940e4c

十二、决策边界(Decision Boundary)

用于显示分类模型的决策边界。

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

# 示例数据
X, y = make_blobs(n_samples=100, centers=2, random_state=6)
clf = SVC(kernel='linear').fit(X, y)

# 绘制决策边界
xx, yy = np.meshgrid(np.linspace(-10, 10, 500), np.linspace(-10, 10, 500))
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, levels=[Z.min(), 0, Z.max()], cmap='viridis', alpha=0.5)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Decision Boundary')
plt.show()

1763012479405-943598ee-48a3-48b5-8371-1c6aa440069b

十三、算法对比图

import matplotlib.pyplot as plt
import numpy as np

# 示例数据:不同算法在迭代过程中的目标函数值
iterations = np.arange(1, 101)
alg1_performance = np.log(iterations) + np.random.randn(100) * 0.1
alg2_performance = np.log(iterations) * 1.1 + np.random.randn(100) * 0.1
alg3_performance = np.log(iterations) * 0.9 + np.random.randn(100) * 0.1

# 绘制算法对比图
plt.plot(iterations, alg1_performance, label='Algorithm 1', color='b')
plt.plot(iterations, alg2_performance, label='Algorithm 2', color='g')
plt.plot(iterations, alg3_performance, label='Algorithm 3', color='r')
plt.xlabel('Iteration')
plt.ylabel('Objective Value')
plt.title('Algorithm Performance Comparison')
plt.legend()
plt.show()

1763012479463-0a643c25-d278-41a8-a9ad-6adab5af27a7

十四、箱线图(Box Plot)

用于展示数据的集中趋势和分散程度。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# 示例数据
data = [np.random.randn(100) for _ in range(4)]

# 绘制箱线图
sns.boxplot(data=data)
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Box Plot of Data Distribution')
plt.show()

1763012479526-21b01992-8d63-4463-87f1-9a1b4b56c096

十五、人口金字塔(Population Pyramid)

用于显示不同年龄段的人口分布。

import matplotlib.pyplot as plt
import numpy as np

# 示例数据
age_groups = ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70+']
male_population = [500, 600, 700, 800, 700, 600, 500, 400]
female_population = [450, 550, 650, 750, 650, 550, 450, 350]

# 绘制人口金字塔
fig, ax = plt.subplots(figsize=(10, 8))
ax.barh(age_groups, male_population, color='blue', label='Male')
ax.barh(age_groups, [-x for x in female_population], color='red', label='Female')
ax.set_xlabel('Population')
ax.set_title('Population Pyramid')
ax.legend()
plt.show()

1763012479584-d9205e88-ab82-47cf-bb72-2becbb06d9b6

十六、Pareto前沿(Pareto Front)

用于多目标优化的解的可视化

import matplotlib.pyplot as plt
import numpy as np

# 生成示例数据:多目标优化问题的结果
np.random.seed(0)
objectives = np.random.rand(100, 2)

# 计算Pareto前沿
def pareto_frontier(points):
sorted_points = points[np.argsort(points[:, 0])]
pareto_front = [sorted_points[0]]
for point in sorted_points[1:]:
if point[1] < pareto_front[-1][1]:
pareto_front.append(point)
return np.array(pareto_front)

pareto_front = pareto_frontier(objectives)

# 绘制Pareto前沿线
plt.scatter(objectives[:, 0], objectives[:, 1], label='Objective Points')
plt.plot(pareto_front[:, 0], pareto_front[:, 1], color='red', label='Pareto Front')
plt.xlabel('Objective 1')
plt.ylabel('Objective 2')
plt.title('Pareto Front')
plt.legend()
plt.show()

1763012479642-037f5688-d8f5-4b29-aae2-0371018062ec