In [1]:
import numpy as np
import scipy.stats as stats
import pymc3 as pm
import matplotlib.pyplot as plt
plt.style.use(['ggplot', 'seaborn-talk'])
%matplotlib inline
In [2]:
#loading the data
NIRS_vals = []
with open("NIRS_data.txt", "r") as spfile:
for line in spfile:
NIRS_vals.append(np.float(line))
NIRS_vals = np.array(NIRS_vals)
In [3]:
NIRS_vals.shape[0]
Out[3]:
The dataset consists of Near-Infrared Spectrographic (NIRS) readings of oxygenated haemoglobin concentrations tracking frontal lobe activity.
The data has been gathered during an attention task in ADHD adults.
Because of the attention task, a change is expected in the time series of NIRS values and a simple plot of the data shows it to be the case.
Eyeball estimates put the change to occur around around 750 unit of time.
We need to make an inference concerning this change point.
In [4]:
plt.figure(figsize=(17,8))
plt.scatter(np.arange(NIRS_vals.shape[0]), NIRS_vals, color='red', alpha=0.4)
plt.axvline(750, lw=10, color='dodgerblue', alpha=0.2)
plt.xlabel('Time')
plt.ylabel('NIRS value')
plt.show()
In [5]:
len_time = NIRS_vals.shape[0]
time_indx = np.arange(len_time)
adhd_model = pm.Model()
with adhd_model:
#priors
mus_0 = pm.Normal('mu_0', 0, 1000)
mus_1 = pm.Normal('mu_1', 0, 1000)
prec = pm.Gamma('prec', alpha=0.001, beta=0.001)
comm_dev = pm.Deterministic('st_dev', np.sqrt(1/prec))
tau = pm.DiscreteUniform('tau', lower=0, upper=len_time)
mu_s = pm.math.switch(time_indx < tau, mus_0, mus_1)
#likelihood
nirs_val = pm.Normal('NIRS_val', mu=mu_s, sd=comm_dev, observed=NIRS_vals)
In [6]:
with adhd_model:
trace_nirs = pm.sample(10000)
In [12]:
plt.figure(figsize=(12,7))
plt.title('Histogram of the posterior of the time-change parameter')
plt.hist(trace_nirs['tau'][100:], bins=100, normed=1, color='crimson', alpha=0.7)
plt.show()
In [8]:
tau_MAP = stats.mode(trace_nirs['tau'])
print (tau_MAP)
In [11]:
plt.figure(figsize=(17,8))
plt.ylim([0, NIRS_vals.max()+np.abs(NIRS_vals.min())])
colbrew = ['#e41a1c', '#984ea3', '#4daf4a', '#2b83ba']
plt.scatter(np.arange(NIRS_vals.shape[0]), NIRS_vals, color=colbrew[0], alpha=0.4)
plt.plot((0,tau_MAP[0]),
(NIRS_vals[:np.int(tau_MAP[0])].mean(), NIRS_vals[:np.int(tau_MAP[0])].mean()),
color=colbrew[1], ls='--', label='mean before change')
plt.plot((tau_MAP[0], NIRS_vals.shape[0]),
(NIRS_vals[np.int(tau_MAP[0]):].mean(), NIRS_vals[np.int(tau_MAP[0]):].mean()),
color=colbrew[2], ls='--', label='mean after change')
plt.axvline(tau_MAP[0], lw=3, color=colbrew[-1], alpha=0.7, label='Est. time of change')
plt.xlabel('Time')
plt.ylabel('NIRS value')
plt.legend()
plt.show()
In [ ]: