Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stuff about joint distribution #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,145 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
Repozitář pro přípravu na zkoušku z NI-VSM na FIT ČVUT.

Za funkční příklady a další díky [@tenhobi](https://github.com/tenhobi)
Forked from [@pokorj54](https://github.com/pokorj54)

Za funkční příklady a další díky [@tenhobi](https://github.com/tenhobi)
107 changes: 107 additions & 0 deletions joint_probability_distribution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import numpy as np
from scipy.stats.contingency import margins


def entropy(array):
"""
Calculates the entropy of a discrete random variable
:param array: probabilities of the discrete random variable
:return: Entropy of the discrete random variable described by array
"""
return -1 * np.sum(array * np.log2(array))


def relative_entropy(p, q):
"""
Calculates the Kullback-Leibler distance between two discrete random variables p, q D(p||q)
:param p: discrete random variable
:param q: discrete random variable
:return: Kullback-Leibler distance D(p||q)
"""
logarithms = np.log2(p / q, out=np.zeros_like(p), where=(p != 0))
return np.sum(np.multiply(p, logarithms))


class JointProbabilityDistribution:
def __init__(self, matrix):
self.matrix = matrix

@property
def all(self):
marginal_distributions = self.marginal_distributions
conditional_entropy = self.conditional_entropy
return {
'marginal distribution x': marginal_distributions[0],
'marginal distribution y': marginal_distributions[1],
'joined entropy': self.joined_entropy,
'marginal entropy x': entropy(marginal_distributions[0]),
'marginal entropy y': entropy(marginal_distributions[1]),
'conditional entropy x|y': conditional_entropy[0],
'conditional entropy y|x': conditional_entropy[1],
'relative entropy x||y': self.relative_entropy('x'),
'relative entropy y||x': self.relative_entropy('y'),
'joined distribution': self.matrix
}

@property
def marginal_distributions(self):
x, y = margins(self.matrix)
return x.T.flatten(), y.flatten()

@property
def joined_entropy(self):
logarithms = np.log2(self.matrix, out=np.zeros_like(self.matrix), where=(self.matrix != 0))
products = np.multiply(self.matrix, logarithms)
return -1 * np.sum(products)

@property
def conditional_entropy(self):
return self.__conditional_entropy(axis=0), self.__conditional_entropy(axis=1)

def relative_entropy(self, first='x'):
marginal_distributions = self.marginal_distributions

if first == 'x':
p, q = marginal_distributions
elif first == 'y':
q, p = marginal_distributions
else:
raise ValueError('Permitted values: {x,y}')
return relative_entropy(p, q)

@property
def mutual_information(self):
x, y = self.marginal_distributions
p = self.matrix
q = np.multiply(x, y)
return relative_entropy(p, q)

def __conditional_entropy(self, axis=0):
axis_a, axis_b = (0, 1) if axis == 0 else (1, 0)

p_b = self.marginal_distributions[axis_a]

result = 0

for i in range(self.matrix.shape[axis_a]):
for j in range(self.matrix.shape[axis_b]):
if self.matrix[i, j] == 0:
continue
p_xy = self.matrix[i, j]
p_a_given_b = p_xy / p_b[j]
result += p_xy * np.log2(p_a_given_b)

return -1 * result


if __name__ == '__main__':
matrix = np.matrix([
[1 / 8, 1 / 16, 1 / 32, 1 / 32],
[1 / 16, 1 / 8, 1 / 32, 1 / 32],
[1 / 16, 1 / 16, 1 / 16, 1 / 16],
[1 / 4, 0, 0, 0],
])
jointProbabilityDistribution = JointProbabilityDistribution(matrix)

for key, value in jointProbabilityDistribution.all.items():
print(f'{key}: {value}')
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
jupyter
scipy
numpy