判别模型(Discriminative Model)和生成模型(Generative Model)

本文深入探讨了判别模型与生成模型在概率分布上的差异,解释了它们在分类任务中的应用,并讨论了各自的优势与局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一篇:

Let's say you have input data x and you want to classify the data into labels y. A generative model learns the joint probability distribution p(x,y) and adiscriminative model learns the conditional probability distribution p(y|x) - which you should read as 'the probability of y given x'.

Here's a really simple example. Suppose you have the following data in the form (x,y):

       (1,0), (1,0), (2,0), (2, 1)

p(x,y) is

             y=0   y=1
            -----------
       x=1 | 1/2   0
       x=2 | 1/4   1/4

p(y|x) is

             y=0   y=1
            -----------
       x=1 | 1     0
       x=2 | 1/2   1/2

If you take a few minutes to stare at those two matrices, you will understand the difference between the two probability distributions.

The distribution p(y|x) is the natural distribution for classifying a given example x into a class y, which is why algorithms that model this directly are calleddiscriminative algorithms. Generative algorithms model p(x,y), which can be tranformed into p(y|x) by applying Bayes rule and then used for classification. However, the distribution p(x,y) can also be used for other purposes. For example you could use p(x,y) to generate likely (x,y) pairs.

From the description above you might be thinking that generative models are more generally useful and therefore better, but it's not as simple as that. This paper is a very popular reference on the subject of discriminative vs. generative classifiers, but it's pretty heavy going. The overall gist is that discriminative models generally outperform generative models in classification tasks.

第二篇:

  • 判别模型Discriminative Model,又可以称为条件模型,或条件概率模型。估计的是条件概率分布(conditional distribution), p(class|context)。
  • 生成模型Generative Model,又叫产生式模型。估计的是联合概率分布(joint probability distribution),p(class, context)=p(class|context)*p(context)。
### 使用 Python 绘制判别模型生成模型的图表 为了可视化判别模型生成模型的工作原理及其结果,可以通过 `matplotlib` 或 `seaborn` 库实现绘图。以下分别介绍如何针对这两种模型绘制相应的图表。 --- #### 1. 判别模型的图像绘制 对于判别模型,可以绘制决策边界的图形来直观显示模型是如何划分不同类别的数据点。假设我们有一个二分类问题,使用逻辑回归作为判别模型,则可以用如下代码绘制: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification # 创建虚拟数据集 X, y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1) # 训练逻辑回归模型 clf = LogisticRegression() clf.fit(X, y) # 获取网格范围 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, 0.02), np.arange(y_min, y_max, 0.02)) # 预测网格上的值 Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 绘制决策边界 plt.contourf(xx, yy, Z, alpha=0.8, cmap=plt.cm.Paired) plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Discriminative Model Decision Boundary') plt.show() ``` 此代码展示了如何利用二维平面中的数据点对应的类别标签拟合一个逻辑回归模型,并绘制其决策边界[^4]。 --- #### 2. 生成模型的图像绘制 对于生成模型,可以展示生成样本的过程或者生成样本与真实样本之间的对比。这里以 GAN(生成对抗网络)为例,假设有预训练好的生成器模型,我们可以生成一些新样本并与原始数据进行比较。 ```python import numpy as np import matplotlib.pyplot as plt from keras.models import load_model # 加载生成器模型 (假设已保存为 H5 文件) generator = load_model('wgan_generator.h5') # 定义噪声向量 noise_dim = 100 num_examples_to_generate = 16 seed = np.random.normal(0, 1, (num_examples_to_generate, noise_dim)) # 生成样本 generated_images = generator.predict(seed) # 展示生成的图片 fig, axes = plt.subplots(4, 4, figsize=(6, 6)) axes = axes.flatten() for i, ax in enumerate(axes): img = generated_images[i].reshape((28, 28)) # 假设是 MNIST 数据集 ax.imshow(img, cmap='gray') ax.axis('off') plt.tight_layout() plt.suptitle('Generated Samples from Generative Model', fontsize=16) plt.show() ``` 这段代码演示了如何加载预先训练好的 WGAN 生成器模型,并通过随机噪声输入生成一批新的图像样本[^1]。 --- #### 3. 对比真实数据与生成数据 如果希望进一步分析生成模型的效果,可以将生成的数据与真实的训练数据放在一起作对比。例如,在 MNIST 手写数字数据集中,可以这样操作: ```python from keras.datasets import mnist # 加载真实数据 (train_images, _), (_, _) = mnist.load_data() # 显示部分真实数据 real_images = train_images[:16] fig, axes = plt.subplots(2, 8, figsize=(16, 4)) axes = axes.flatten() for i, ax in enumerate(axes[:len(real_images)]): ax.imshow(real_images[i], cmap='gray') ax.set_title('Real', fontsize=10) ax.axis('off') for i, ax in enumerate(axes[len(real_images):]): ax.imshow(generated_images[i].reshape((28, 28)), cmap='gray') ax.set_title('Generated', fontsize=10) ax.axis('off') plt.tight_layout() plt.suptitle('Comparison of Real and Generated Data', fontsize=16) plt.show() ``` 该脚本会同时呈现真实数据生成数据,便于观察两者的相似程度。 --- ### 总结 以上介绍了如何用 Python 中的 `matplotlib` `seaborn` 库绘制判别模型的决策边界以及生成模型的生成样本。这些可视化的工具可以帮助更好地理解解释模型的行为。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值