【数据处理】Python:实现求条件分布函数 | 求平均值方差和协方差 | 求函数函数期望值的函数 | 概率论

news2024/9/21 0:46:13

   猛戳订阅! 👉 《一起玩蛇》🐍

💭 写在前面:本章我们将通过 Python 手动实现条件分布函数的计算,实现求平均值,方差和协方差函数,实现求函数期望值的函数。部署的测试代码放到文后了,运行所需环境 python version >= 3.6,numpy >= 1.15,nltk >= 3.4,tqdm >= 4.24.0,scikit-learn >= 0.22。

🔗 相关链接:【概率论】Python:实现求联合分布函数 | 求边缘分布函数

📜 本章目录:

0x00 实现求条件分布的函数(Conditional distribution)

0x01 实现求平均值, 方差和协方差的函数(Mean, Variance, Covariance)

0x02 实现求函数期望值的函数(Expected Value of a Function)

0x04 提供测试用例


0x00 实现求条件分布的函数(Conditional distribution)

实现 conditional_distribution_of_word_counts 函数,接收 Point 和 Pmarginal 并求出结果。

请完成下面的代码,计算条件分布函数 (Joint distribution),将结果存放到 Pcond 中并返回:

def conditional_distribution_of_word_counts(Pjoint, Pmarginal):
    """
    Parameters:
    Pjoint (numpy array) - Pjoint[m,n] = P(X0=m,X1=n), where
      X0 is the number of times that word0 occurs in a given text,
      X1 is the number of times that word1 occurs in the same text.
    Pmarginal (numpy array) - Pmarginal[m] = P(X0=m)

    Outputs:
    Pcond (numpy array) - Pcond[m,n] = P(X1=n|X0=m)
    """
    raise RuntimeError("You need to write this part!")
    return Pcond

​

🚩 输出结果演示:

Problem3. Conditional distribution:
[[0.97177419 0.02419355 0.00201613 0.        0.00201613]
 [1.         0.         0.         0.        0.        ]
 [       nan        nan        nan       nan        nan]
 [       nan        nan        nan       nan        nan]
 [1.         0.         0.         0.        0.        ]]

💭 提示:条件分布 (Conditional distribution) 公式如下:

\color{}P=(X_1=x_1|X_0=x_0)=\frac{P(X_0=X_0,X_1=x_1)}{P(X_0=x_0)}

💬 代码演示:conditional_distribution_of_word_counts 的实现

def conditional_distribution_of_word_counts(Pjoint, Pmarginal):
    Pcond = Pjoint / Pmarginal[:, np.newaxis]  # 根据公式即可算出条件分布
    return Pcond

值得注意的是,如果分母 Pmarginal 中的某些元素为零可能会导致报错问题。这导致除法结果中出现了 NaN(Not a Number)。在计算条件概率分布时,如果边缘分布中某个值为零,那么条件概率无法得到合理的定义。为了解决这个问题,我们可以在计算 Pmarginal 时,将所有零元素替换为一个非零的很小的数,例如 1e-10。

0x01 实现求平均值, 方差和协方差的函数(Mean, Variance, Covariance)

使用英文文章中最常出现的 a, the 等单词求出其联合分布 (Pathe) 和边缘分布 (Pthe)。

Pathe 和 Pthe 在 reader.py 中已经定义好了,不需要我们去实现,具体代码文末可以查阅。

这里需要我们使用概率分布,编写求平均值、方差和协方差的函数:

  • 函数 mean_from_distribution 和 variance_from_distribution 输入概率分布 \color{}P(Pthe) 中计算概率变量 \color{}X 的平均和方差并返回。平均值和方差保留小数点前三位即可。
  • 函数 convariance_from_distribution 计算概率分布 \color{}P(Pathe) 中的概率变量 \color{}X_0 和概率变量 \color{}X_1 的协方差并返回,同样保留小数点前三位即可。

def mean_from_distribution(P):
    """
    Parameters:
    P (numpy array) - P[n] = P(X=n)

    Outputs:
    mu (float) - the mean of X
    """
    raise RuntimeError("You need to write this part!")
    return mu


def variance_from_distribution(P):
    """
    Parameters:
    P (numpy array) - P[n] = P(X=n)

    Outputs:
    var (float) - the variance of X
    """
    raise RuntimeError("You need to write this part!")
    return var


def covariance_from_distribution(P):
    """
    Parameters:
    P (numpy array) - P[m,n] = P(X0=m,X1=n)

    Outputs:
    covar (float) - the covariance of X0 and X1
    """
    raise RuntimeError("You need to write this part!")
    return covar

🚩 输出结果演示:

Problem4-1. Mean from distribution:
4.432
Problem4-2. Variance from distribution:
41.601
Problem4-3. Convariance from distribution:
9.235

💭 提示:求平均值、方差和协方差的公式如下

\color{}\mu =\sum_{x}^{}x\cdot P(X=x)

\color{}\sigma =\sum_{x }^{}(x-\mu )^2\cdot P(X=x)

\color{}\, Cov(X_0,X_1)=\sum_{x_0,x_1}^{}(x_0-\mu x_0)(x_1-\mu x_1)\cdot P(X_0=x_0,X_1=x_1)

💬 代码演示:

def mean_from_distribution(P):
    mu = np.sum(    # Σ
        np.arange(len(P)) * P
    )

    return round(mu, 3)  # 保留三位小数

def variance_from_distribution(P):
    mu = mean_from_distribution(P)
    var = np.sum(    # Σ
        (np.arange(len(P)) - mu) ** 2 * P
    )

    return round(var, 3)   # 保留三位小数


def covariance_from_distribution(P):
    m, n = P.shape
    mu_X0 = mean_from_distribution(np.sum(P, axis=1))
    mu_X1 = mean_from_distribution(np.sum(P, axis=0))
    covar = np.sum(   # Σ
        (np.arange(m)[:, np.newaxis] - mu_X0) * (np.arange(n) - mu_X1) * P
    )

    return round(covar, 3)

0x02 实现求函数期望值的函数(Expected Value of a Function)

实现 expectation_of_a_function 函数,计算概率函数 \color{}X_0,X_1 的 \color{}E[f(X_0,X_1)] 。

其中 \color{}P 为联合分布,\color{}f 为两个实数的输入,以 \color{}f(x_0,x_1)  的形式输出。

函数 \color{}f 已在 reader.py 中定义,你只需要计算 \color{}E[f(X_0,X_1)] 的值并保留后三位小数返回即可。

def expectation_of_a_function(P, f):
    """
    Parameters:
    P (numpy array) - joint distribution, P[m,n] = P(X0=m,X1=n)
    f (function) - f should be a function that takes two
       real-valued inputs, x0 and x1.  The output, z=f(x0,x1),
       must be a real number for all values of (x0,x1)
       such that P(X0=x0,X1=x1) is nonzero.

    Output:
    expected (float) - the expected value, E[f(X0,X1)]
    """
    raise RuntimeError("You need to write this part!")
    return expected

🚩 输出结果演示:

Problem5. Expectation of a funciton:
1.772

💬 代码演示:expectation_of_a_function 函数的实现

def expectation_of_a_function(P, f):
    """
    Parameters:
    P (numpy array) - joint distribution, P[m,n] = P(X0=m,X1=n)
    f (function) - f should be a function that takes two
       real-valued inputs, x0 and x1.  The output, z=f(x0,x1),
       must be a real number for all values of (x0,x1)
       such that P(X0=x0,X1=x1) is nonzero.

    Output:
    expected (float) - the expected value, E[f(X0,X1)]
    """
    m, n = P.shape
    E = 0.0

    for x0 in range(m):
        for x1 in range(n):
            E += f(x0, x1) * P[x0, x1]

    return round(E, 3)   # 保留三位小数

0x04 提供测试用例

这是一个处理文本数据的项目,测试用例为 500 封电子邮件的数据(txt 的格式文件):

🔨 所需环境:

- python version >= 3.6
- numpy >= 1.15
- nltk >= 3.4
- tqdm >= 4.24.0
- scikit-learn >= 0.22

nltk 是 Natural Language Toolkit 的缩写,是一个用于处理人类语言数据(文本)的 Python 库。nltk 提供了许多工具和资源,用于文本处理和 NLP,PorterStemmer 用来提取词干,用于将单词转换为它们的基本形式,通常是去除单词的词缀。 RegexpTokenizer 是基于正则表达式的分词器,用于将文本分割成单词。

💬 data_load.py:用于加载文本数据

import os
import numpy as np
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import RegexpTokenizer
from tqdm import tqdm

porter_stemmer = PorterStemmer()
tokenizer = RegexpTokenizer(r"\w+")
bad_words = {"aed", "oed", "eed"}  # these words fail in nltk stemmer algorithm


def loadFile(filename, stemming, lower_case):
    """
    Load a file, and returns a list of words.

    Parameters:
    filename (str): the directory containing the data
    stemming (bool): if True, use NLTK's stemmer to remove suffixes
    lower_case (bool): if True, convert letters to lowercase

    Output:
    x (list): x[n] is the n'th word in the file
    """
    text = []
    with open(filename, "rb") as f:
        for line in f:
            if lower_case:
                line = line.decode(errors="ignore").lower()
                text += tokenizer.tokenize(line)
            else:
                text += tokenizer.tokenize(line.decode(errors="ignore"))
    if stemming:
        for i in range(len(text)):
            if text[i] in bad_words:
                continue
            text[i] = porter_stemmer.stem(text[i])
    return text


def loadDir(dirname, stemming, lower_case, use_tqdm=True):
    """
    Loads the files in the folder and returns a
    list of lists of words from the text in each file.

    Parameters:
    name (str): the directory containing the data
    stemming (bool): if True, use NLTK's stemmer to remove suffixes
    lower_case (bool): if True, convert letters to lowercase
    use_tqdm (bool, default:True): if True, use tqdm to show status bar

    Output:
    texts (list of lists): texts[m][n] is the n'th word in the m'th email
    count (int): number of files loaded
    """
    texts = []
    count = 0
    if use_tqdm:
        for f in tqdm(sorted(os.listdir(dirname))):
            texts.append(loadFile(os.path.join(dirname, f), stemming, lower_case))
            count = count + 1
    else:
        for f in sorted(os.listdir(dirname)):
            texts.append(loadFile(os.path.join(dirname, f), stemming, lower_case))
            count = count + 1
    return texts, count

💬 reader.py:将读取数据并打印

import data_load, hw4, importlib
import numpy as np

if __name__ == "__main__":
    texts, count = data_load.loadDir("data", False, False)

    importlib.reload(hw4)
    Pjoint = hw4.joint_distribution_of_word_counts(texts, "mr", "company")
    print("Problem1. Joint distribution:")
    print(Pjoint)
    print("---------------------------------------------")

    P0 = hw4.marginal_distribution_of_word_counts(Pjoint, 0)
    P1 = hw4.marginal_distribution_of_word_counts(Pjoint, 1)
    print("Problem2. Marginal distribution:")
    print("P0:", P0)
    print("P1:", P1)
    print("---------------------------------------------")

    Pcond = hw4.conditional_distribution_of_word_counts(Pjoint, P0)
    print("Problem3. Conditional distribution:")
    print(Pcond)
    print("---------------------------------------------")

    Pathe = hw4.joint_distribution_of_word_counts(texts, "a", "the")
    Pthe = hw4.marginal_distribution_of_word_counts(Pathe, 1)

    mu_the = hw4.mean_from_distribution(Pthe)
    print("Problem4-1. Mean from distribution:")
    print(mu_the)

    var_the = hw4.variance_from_distribution(Pthe)
    print("Problem4-2. Variance from distribution:")
    print(var_the)

    covar_a_the = hw4.covariance_from_distribution(Pathe)
    print("Problem4-3. Covariance from distribution:")
    print(covar_a_the)
    print("---------------------------------------------")

    def f(x0, x1):
        return np.log(x0 + 1) + np.log(x1 + 1)

    expected = hw4.expectation_of_a_function(Pathe, f)
    print("Problem5. Expectation of a function:")
    print(expected)

📌 [ 笔者 ]   王亦优
📃 [ 更新 ]   2023.11.15
❌ [ 勘误 ]   /* 暂无 */
📜 [ 声明 ]   由于作者水平有限,本文有错误和不准确之处在所难免,
              本人也很想知道这些错误,恳望读者批评指正!

📜 参考资料 

C++reference[EB/OL]. []. http://www.cplusplus.com/reference/.

Microsoft. MSDN(Microsoft Developer Network)[EB/OL]. []. .

百度百科[EB/OL]. []. https://baike.baidu.com/.

比特科技. C++[EB/OL]. 2021[2021.8.31]. 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1212501.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言--五子棋项目【图文详解 经典】

今天小编带领大家学一学C语言入门必写的五子棋项目,题目非常经典,值得一学。 目录 一.目标效果 二.五子棋的元素 1.棋子 2.棋盘 三,需要准备的工具 四.具体内容 1.加载背景图片 2.画横线与竖线 3. 画小黑点 4.获取鼠标消息 5.画棋子 6.如何判断比…

【java学习—十五】创建多线程的两种方式(2)

文章目录 1. 多线程的创建和启动2. Thread 类3. 创建多线程的两种方式3.1.继承Thread类实现多线程3.1.1. 举例3.1.2. 举例2 3.2. 实现Runnable接口3.2.1. 举例13.2.2. 举例2 4. 继承方式和实现方式的联系与区别5. 使用多线程的优点 1. 多线程的创建和启动 Java 语言的 JVM 允许…

【差分演化算法相关文献总结】

差分演化算法相关文献总结 前言概述文献综述总结 前言 本人作为一名从事了三年演化算法研究的菜鸡研究生,其中大部分时间都在专注于差分演化算法(Differential Evolution, DE)的相关研究。现如今已经毕业,回顾往昔,经过…

跌破1940后金价直指1900 对黄金代理是好是坏?

受以鲍威尔为首的美联储官员近期讲话的影响,加上巴以冲突暂时出现降温,导致避险需求下降,在两大因素的影响之下,现货黄金行情在近期的大涨之后出现大跌。金价不光跌破1950关口,在跌穿1940后势头更是直指1900。金价在一…

虹科干货丨Lambda数据架构和Kappa数据架构——构建现代数据架构

文章来源:虹科云科技 虹科干货丨Lambda数据架构和Kappa数据架构——构建现代数据架构 如何更好地构建我们的数据处理架构,如何对IT系统中的遗留问题进行现代化改造并将其转变为现代数据架构?该怎么为你的需求匹配最适合的架构设计呢&#xf…

异常--Java

cry…catch使用 /*需求:测试除法器(try...catch)* 测试人:小王* 测试日期:2023/11/15* */ package yichang_test1;import java.util.InputMismatchException; import java.util.Scanner;public class TestException2 …

cadence virtuoso layout 无法跑DRC

问题:无法跑DRC could not establish connection with Calibre Interactiveon socket localhost 7000. 尝试: 点击一下红框右边的connect。 (此法不一定有用,死马当活马医)

Page分页records有数据,但是total=0,解决办法

Page分页records有数据,但是total0,解决办法 问题:程序运行起来后,后端接收前端传来的搜索请求信息正常,但无法在前端正确反馈信息,通过在后端排查发现total一直等于零,但数据库中有数据&#x…

大数据-之LibrA数据库系统告警处理(ALM-12046 网络写包丢包率超过阈值)

告警解释 系统每30秒周期性检测网络写包丢包率,并把实际丢包率和阈值(系统默认阈值0.5%)进行比较,当检测到网络写包丢包率连续多次(默认值为5)超过阈值时产生该告警。 用户可通过“系统设置 > 阈值配置…

OpenCV的应用——道路边缘检测

OpenCV(Open Source Computer Vision Library)是一个开源的计算机视觉库,它提供了丰富的图像处理和计算机视觉算法,使得开发者可以便捷地进行图像处理、对象识别、图像分割等任务。道路边缘检测是计算机视觉中的重要应用之一&…

帝国CMS仿核弹头H5小游戏模板/帝国CMS内核仿游戏网整站源码

帝国CMS仿核弹头H5小游戏模板,帝国CMS内核仿游戏网整站源码。比较适合小游戏发布、APP应用资讯类网站使用,有兴趣的可以二次开发试试。 下载地址:https://bbs.csdn.net/topics/617579435

uniapp基础学习笔记01

文章目录 本博客根据黑马教程学习uniapp一、技术架构二、创建项目2.1 Hbuilder创建2.2 插件安装2.3 微信开发者工具配置与运行2.3.1 简单修改基础页面 2.4 pages.json和tabBar2.4.1 pages.json与tabBar配置2.4.2 案例 三、uniapp与原生开发的区别 本博客根据黑马教程学习uniapp…

C# Socket通信从入门到精通(10)——如何检测两台电脑之间的网络是否通畅

前言: 我们在完成了socket通信程序开发以后,并且IP地址也设置好以后,可以先通过一些手段来测试两台电脑之间的网络是否通畅,如果确认了网络通畅以后,我们再测试我们编写的Socket程序。 1、同时按下键盘的windows键+"R"键,如下图: 下面两张图是两种键盘的情…

参考意义大。4+巨噬细胞相关生信思路,简单易复现。

今天给同学们分享一篇生信文章“Angiogenesis regulators S100A4, SPARC and SPP1 correlate with macrophage infiltration and are prognostic biomarkers in colon and rectal cancers”,这篇文章发表在Front Oncol期刊上,影响因子为4.7。 结果解读&a…

【探索Linux】—— 强大的命令行工具 P.15(进程间通信 —— system V共享内存)

阅读导航 引言一、system V的概念二、共享内存(1) 概念(2) 共享内存示意图(3) 共享内存数据结构 三、共享内存的使用1. 共享内存的使用步骤(1)包含头文件(2)获取键值(ftok函数)(3)创…

LeetCode - 142. 环形链表 II (C语言,快慢指针,配图)

如果你对快慢指针,环形链表有疑问,可以参考下面这篇文章,了解什么是环形链表后,再做这道题会非常简单,也更容易理解下面的图片公式等。 LeetCode - 141. 环形链表 (C语言,快慢指针,…

写作脑科学——屠龙的高效写作指南

ISBN: 978-7-115-59231-6 作者:杨滢(屠龙的胭脂井) 页数:201页 阅读时间:2023-09-09 推荐指数:★★★★★ 十分推荐这本书,写的非常简单易懂,里面有很多方法论和实用技巧&#xff0c…

使用Maxent模型预测适生区

Maxent模型因其在潜在适生区预测中稳健的表现,时下已经成为使用最广泛的物种分布模型。biomod虽然可以通过集成模型的优势来弥补数据量较小的劣势,但是其在使用和运算时间上的优势远不如Maxent,虽然最新的biomod2已经修复了一些bug&#xff0…

Power Apps-使用power Automate流

创建:Power Automate-创建power Apps使用的流-CSDN博客 打开Power Apps,创建页面,添加三个输入框(分别是换算前单位、换算后单位、货币数),和一个文本框(输出结果)以及一个按钮 在…

微信聚合聊天,自动回复

微信,这款融合通讯、社交、娱乐、小程序于一体的平台,已经深深融入我们的日常生活。作为我们日常生活中不可或缺的社交工具,尤其在工作中,我们需要通过微信来沟通客户,这个时候我们就会希望有快速回复客户的方式秒回客…