简体   繁体   English

[Python - scipy]:从自定义多元概率密度生成随机样本 Function (PDF)

[英][Python - scipy]: Genarate random samples from custom multivariate Probability Density Function (PDF)

I want to generate random sample (vector X) :我想生成随机样本(向量 X)

X = [x1, x2, x3, ..., x_d]

where X follows a custom multivariate Probability Density Function .其中X 遵循自定义多元概率密度 Function

I am using Python - scipy and I overvide the PDF function to follow a combination of multivariate normal distributions.我正在使用Python - scipy并且我覆盖了 PDF function 以遵循多元正态分布的组合。

For example:例如:

import plotly.graph_objects as go
import numpy as np
from scipy.stats._multivariate import multivariate_normal_gen, multivariate_normal, _squeeze_output


class multivar_rv(multivariate_normal_gen):

    def pdf(self, x, mean=None, cov=1, allow_singular=True):
        mean = [
            [0, 1],
            [2, 5]
        ]
        cov = [
            [
                [1, 0],
                [0, 1]
            ],
            [
                [1.5, 0],
                [0, 1.5]
            ]
        ]
        weight = [.5, .5]
        return sum(weight[i] * multivariate_normal(mean[i], cov[i]).pdf(x) for i in range(len(mean)))

The following image shows the plot of the above code.下图为上述代码的plot。 在此处输入图像描述

Now I want to generate samples given the above distribution , however if I use rvs() (from scipy.stats._multivariate.multivariate_normal_gen) the function is not overrided and the results will be generated from the default normal distribution:现在我想根据上述分布生成样本,但是如果我使用rvs() (来自 scipy.stats._multivariate.multivariate_normal_gen),function 不会被覆盖,结果将从默认正态分布生成:

P.rvs()

What do I have to do in order to change this and override this function so that the generated samples follow my PDF?我必须做什么才能更改它并覆盖这个 function,以便生成的样本遵循我的 PDF?

Thank you!谢谢!

That is because the the rvs method that your class inherits (ie that of multivariate_normal_gen) uses an instance of multivariate_normal_gen directly that is declared outside of the class definition ( see lines 657 and 682 in the source ) to generate samples.这是因为您的 class 继承的 rvs 方法(即 multivariate_normal_gen 的方法)直接使用在 class 定义之外声明的 multivariate_normal_gen 实例( 参见源代码中的第 657 和 682 行)来生成样本。 You have to write your own rvs method explicitly.您必须显式编写自己的 rvs 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM