Commit 4029a3f9 authored by Larkin Heintzman's avatar Larkin Heintzman

added figures and trust_model

parent b554e2b2
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import numpy as np
import scipy.stats as ss
import elfi
import matplotlib.pyplot as plt
def MA2(t1, t2, n_obs=100, batch_size=1, random_state=None):
# Make inputs 2d arrays for numpy broadcasting with w
t1 = np.asanyarray(t1).reshape((-1, 1))
t2 = np.asanyarray(t2).reshape((-1, 1))
random_state = random_state or np.random
w = random_state.randn(batch_size, n_obs+2) # i.i.d. sequence ~ N(0,1)
x = w[:, 2:] + t1*w[:, 1:-1] + t2*w[:, :-2]
return x
def autocov(x, lag=1):
C = np.mean(x[:,lag:] * x[:,:-lag], axis=1)
return C
if __name__ == "__main__":
# Set an arbitrary seed and a global random state to keep the randomly generated quantities the same between runs
seed = 20170530 # this will be separately given to ELFI
np.random.seed(seed)
# true parameters
t1_true = 0.6
t2_true = 0.2
y_obs = MA2(t1_true, t2_true)
# Plot the observed sequence
plt.figure(figsize=(11, 6));
plt.plot(y_obs.ravel());
# To illustrate the stochasticity, let's plot a couple of more observations with the same true parameters:
plt.plot(MA2(t1_true, t2_true).ravel());
plt.plot(MA2(t1_true, t2_true).ravel());
# a node is defined by giving a distribution from scipy.stats together with any arguments (here 0 and 2)
t1 = elfi.Prior('uniform', 0, 2)
# ELFI also supports giving the scipy.stats distributions as strings
t2 = elfi.Prior('uniform', 0, 2)
Y = elfi.Simulator(MA2, t1, t2, observed = y_obs)
S1 = elfi.Summary(autocov, Y, 1)
S2 = elfi.Summary(autocov, Y, 2) # the optional keyword lag is given the value 2
# Finish the model with the final node that calculates the squared distance (S1_sim-S1_obs)**2 + (S2_sim-S2_obs)**2
d = elfi.Distance('euclidean', S1, S2)
rej = elfi.Rejection(d, batch_size=10000, seed=seed)
N = 1000
# You can give the sample method a `vis` keyword to see an animation how the prior transforms towards the
# posterior with a decreasing threshold.
result = rej.sample(N, quantile=0.01)
result2 = rej.sample(N, threshold=0.2)
smc = elfi.SMC(d, batch_size=10000, seed = seed)
schedule = [0.7, 0.2, 0.05]
result_smc = smc.sample(N, schedule)
print("quantile results:")
print(result.summary())
print("threshold results:")
print(result2.summary())
print("smc results:")
print(result_smc.summary(all=True))
# plt.show()
This diff is collapsed.
import numpy as np
from trust_model.base_model import HumanTrust
import pdb
class MCTrust(HumanTrust):
def __init__(self, pNames, mcRanges, firstStep):
super().__init__() # python magic
# mcRanges is dictionary that holds parameter names and ranges for each iteration of monte carlo
self.parameterNames = pNames;
self.parameterRanges = {};
self.mcRanges = mcRanges
self.stepSets(firstStep)
def stepSets(self, step = 0):
for p, pName in enumerate(self.parameterNames):
self.parameterRanges[pName] = self.mcRanges[step][p]
self.randParameters()
# pdb.set_trace()
return self.parameterRanges
def randParameters(self):
# first set parameters, then randomize based on ranges
self.setParameters()
for (pName, pRange) in self.parameterRanges.items():
# overwrite w random garbage
self.__dict__[pName] = pRange[0] + pRange[1]*np.random.rand();
#
# def load_sets(self, sets):
# # load in sets of values to plug in for each variable
# # sets is list of tuples, (name, values)
# for i, pair in enumerate(sets):
# if pair[0] in dir(self):
# self.vars.update({pair[0] : (pair[1], pair[2])})
#
# # load initial values
# for ky, val in self.vars.items():
# self.__dict__[ky] = val[0][0]
#
# # figure out active variables, variables that'll change
#
# def step_sets(self):
# # step variables and re-init
# for ky, val in self.vars.items():
# if val[1] == 0: # columns
# if self.cstep == len(val[0]):
# self.__dict__[ky] = val[0][0] # reset
# row_flag = True
# self.cstep = 1
# else:
# self.__dict__[ky] = val[0][self.cstep]
# row_flag = False
# self.cstep = self.cstep + 1
#
# elif val[1] == 1 and row_flag: # rows
#
# # if self.rstep == len(val[0]):
# # self.rstep = 1
# if self.rstep < len(val[0]): # hack tastic
# self.__dict__[ky] = val[0][self.rstep]
# self.rstep = self.rstep + 1
#
# self.reset()
# return self.cstep, self.rstep
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment