Skip to content

Instantly share code, notes, and snippets.

@Nishnha
Created November 23, 2017 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nishnha/811c2f9eb9d6f7d873a1956ad9929c07 to your computer and use it in GitHub Desktop.
Save Nishnha/811c2f9eb9d6f7d873a1956ad9929c07 to your computer and use it in GitHub Desktop.
Expectation-Maximization Calculator for Two Normal Distributions
import math
print("This program assumes a standard deviation of 1 for k=2 normal distributions")
print("Enter your initial values (on separate lines) and a blank line when you've finished.")
# Takes in an unknown number of value arguments.
initialVals = []
while True:
val = input()
if val == "":
break
initialVals.append(val)
u1, u2 = input('Enter your intial h values: ').split()
u1 = float(u1)
u2 = float(u2)
def probabilityU1(x):
x = float(x)
return math.exp( (-1/2) * math.pow((u1 - x), 2) ) / ( math.exp( (-1/2) * math.pow((u1 - x), 2) ) + math.exp( (-1/2) * math.pow((u2 - x), 2) ) )
def probabilityU2(x):
return 1 - probabilityU1(x)
def newBound(probabilityFunction):
numerator = []
denominator = []
for x in initialVals:
numerator.append( float(x) * probabilityFunction(x) )
denominator.append( probabilityFunction(x) )
return sum(numerator) / sum(denominator)
for index, value in enumerate(initialVals):
print('x' + str(index + 1) + ': ' + str(value))
print('E[z' + str(index + 1) + '1]: ' + str(probabilityU1(value)) )
print('E[z' + str(index + 1) + '2]: ' + str(probabilityU2(value)) )
print("New u1 bound: " + str(newBound(probabilityU1)))
print("New u2 bound: " + str(newBound(probabilityU2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment