# Correctly applying switchpoint model?

**URL:** <https://discourse.pymc.io/t/correctly-applying-switchpoint-model/3143>\
**Category:** Questions\
**Created:** [April 23, 2019, 4:27am UTC](https://discourse.pymc.io/t/correctly-applying-switchpoint-model/3143 "2019-04-23T04:27:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gon\_F](https://avatars.discourse-cdn.com/v4/letter/g/f14d63/32.png) [@Gon\_F](https://discourse.pymc.io/u/Gon_F)\
**Post date:** [April 23, 2019, 4:27am UTC](https://discourse.pymc.io/t/correctly-applying-switchpoint-model/3143/1 "2019-04-23T04:27:09Z")

</div>

So, I was interested in learning how to model switchpoints, and after reading some discussions (some links [here](https://discourse.pymc.io/t/switch-point-metropolis-tuning/1082/12), [here](https://discourse.pymc.io/t/getting-mass-matrix-contains-zero-on-the-diagonal-when-trying-to-fit-a-piecewise-linear-model/1922/3), and [here](https://joomik.github.io/mining/)), I decided to jump into them with Pymc3.

After playing around a bit, I have a few questions (mostly to do with improving inference), that I would like to ask, and that I hope the very helpful community here will offer some suggestions with.

1. **Data**  
The data I created is a sine wave with basic normal noise at all times, with an upward squared trend coming in at the halfway point. Here is a picture,

 ![download-4](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/e/ee57a99f3f36eefb33d02504fd644b57e4973454.png)

, with the generating code,

```
# First, regular sine wave + normal noise
x = np.linspace(0,40, num=300)
noise1 = np.random.normal(0,0.3,300)
y = np.sin(x) + noise1

# Second, an upward trending starting halfway, with its own normal noise as well
temp = x[150:]
noise2 = 0.004*temp**2 + np.random.normal(0,0.1,150)
y[150:] = y[150:] + noise2

plt.plot(x, y)

```

And the first dummy model that I trained on this dataset, to see how it fared, was

y = \beta\_0 + \beta\_1\sin x + \beta\_2x \ ,

and I can see that it captured the oscillation, as well as upward trend, well enough for such a mis-specified model.

(this graph is generated from my ad hoc posterior predictive checks)

 ![download-6](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/9/9f72d2340e200169a0fe1f789767ad74d384fe3e.png)

1. **1st Switchpoint model**  
Now, unto my real model. I proceeded to create an ideal model to see how well the switchpoint will be calculated.

Generating my traces, three times with three different settings (for robustness):

```
with model_factory1(x_shared, y_shared) as model:
     first_switchpoint_trace = pm.sample(cores=4)
     second_switchpoint_trace = pm.sample(cores=4, draws=3000, tune=3000)
     third_switchpoint_trace = pm.sample(init='advi', chains=8, cores=4, draws=3000, tune=3000, n_init=30000)

```

The results that I get are somewhat disheartening: the traceplots are all over the place, and **none of them** infer the correct switchpoint moment (the 150th data point, or x = 20), and yet the graphs made using my posterior predictive plots all look _almost_ correct?

In addition, the first and last traces show huge chain divergence (which is confusing, since these represent both the easiest **and** hardest to compute chains), because, I imagine, the switchpoint nature of the model confuses some of the chains sometimes?

The traceplots:

 ![download-8](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/f/fc274530650de9ded09b905e530522ab02082866.png)

 ![download-9](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/5/5e359a569c4414340f560d1bcdb8587852c0b934.png)

 ![download-10](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/c/c644229ebef63d869d6e190aed2f83ecf8f3d814.png)

PPC Graphs (all the same):

 ![download-12](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/d/d8ce31e132091b533da6f9cf163dfdecd4079b92.png)

1. **2nd switchpoint model**

For my 2nd Switchpoint model, I basically just followed junpenglao’s recommendation in the [FAQ](https://discourse.pymc.io/t/frequently-asked-questions/74/3) on using a sigmoid function, instead of `pm.math.switch()`, to make the sampler’s life easier when inferring the switchpoint (which is interesting).

The new code:

```
def model_factory2(X, Y):
    
    with pm.Model() as switchpoint_model:

        # Discrete uniform prior for the switchpoint
        switchpoint = pm.DiscreteUniform('switchpoint', lower=X.min(), upper=X.max(), testval=10)
        
        # Priors 
        beta1_offset = pm.Normal('beta1_offset')
        beta1 = pm.Deterministic("beta1", beta1_offset * 3)
        
        beta2_offset = pm.Normal('beta2_offset')
        beta2 = pm.Deterministic("beta2", beta2_offset * 3)
        
        intercept_offset = pm.Normal('intercept_offset', mu=0, sd=1)
        intercept = pm.Deterministic("intercept", intercept_offset * 3)

        std = pm.HalfNormal('std', sd=5)

        # Likelihood
        part1 = intercept + pm.math.dot(pm.math.sin(X), beta1)
                
        part2 = intercept + pm.math.dot(pm.math.sin(X), beta1) + \
                            pm.math.dot(pm.math.sqr(X), beta2)
          
        ## New code      
        weight = tt.nnet.sigmoid(2 * (X - switchpoint))
        model = weight * part1 + (1 - weight) * part2    
        
        y_lik = pm.Normal('y_lik', mu=model, sd=std, observed = Y)
    
    return switchpoint_model

```

The new traceplots now are _much_ better, from the switchpoint location perspective (they are all generally close to x=20), but now my PPC’s looks absolutely mangled and terrible, and I cannot account for how this happened.

(hurray for posterior-predictive checks telling you if your model makes sense?)

 ![download-13](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/4/4abe049de7249b1bb92a2ec2ccc694b82fb778d7.png)

 ![download-14](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/6/6593b81828607ec4060edbc7743997643bba7d90.png)

 ![download-15](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/3/35a08990fe8438706fb5c809818d5d974f3d2d5e.png)

With the abominable PPC:

 ![download-16](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/f/fd47ad22c48bb3a62e345b6addbbf427e9640917.png)

1. **Conclusion**  
Basically, I’m coming away from this with two questions, which I hope much more experienced modelers can elaborate on.

I will appreciate any discussion and tips, and try to report on any progress made on my end.

---

<div class="post-metadata">

**Author:** ![chartl](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/chartl/32/1515_2.png) [@chartl](https://discourse.pymc.io/u/chartl)\
**Post date:** [April 23, 2019, 7:28pm UTC](https://discourse.pymc.io/t/correctly-applying-switchpoint-model/3143/2 "2019-04-23T19:28:02Z")

</div>

There are tiny, tiny issues. Most fundamentally, because `switchpoint` is discrete, MH is used to sample it. This requires a large amount of tuning to explore the space. When you don’t use enough you get what you observed: MH hasn’t spent enough time bouncing around to find the optimal.

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/5/577d7f299fb1687bde62480d9bff5128806bc50a.jpeg)

For MH i tend to use:

```auto
burn_in=10000
tune=5000
with pm.Model() as model:
  ...
  trace = pm.sample(1000, tune=tune + burn_in, chains=8, cores=3)

```

The second (tiny **tiny** ) issue is with

`model = pm.math.switch(switchpoint >= X, part1, part2)`

This should read

`model = pm.math.switch(tt.gt(switchpoint, X), part1, part2)`

The third issue is with

`std = pm.HalfNormal('std', sd=5)`

This puts a lot of weight on error variances _that exceed the range of the data_. Using a more informative prior like

`std = pm.HalfNormal('std', sd=0.5)`

makes a huge difference in both cases.

With these three changes model 1 appears to work just fine:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/b/b2b683f734f21ff17956baac19c3a57dc067d5fd.png)

and with confidence region:

```auto
y_mean = np.mean(ppc['y_lik'], 0)
y_u95 = np.percentile(ppc['y_lik'], 97.5, axis=0)
y_u05 = np.percentile(ppc['y_lik'], 2.5, axis=0)
plt.plot(X, y_mean)
plt.plot(X, y_u95, color='red')
plt.plot(X, y_u05, color='red')

```

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/3/363e080d808b8ce8a863214702639e55a4393d5d.png)

Edit:

Oh and for model 2, I think the sigmoid weights are reversed:

```auto
    w = tt.nnet.sigmoid(2*(X-switchpoint))
    model = (1-w)*part1 + w*part2

```

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/f/f005665fe5969aecdab2bd1de6010e7bb3f899b3.png)

```auto
  model = w*part1 + (1-w)*part2

```

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/5/5c73b9cde2781544befdcd2417758f8ca8952d4c.png)

---

<div class="post-metadata">

**Author:** ![chartl](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/chartl/32/1515_2.png) [@chartl](https://discourse.pymc.io/u/chartl)\
**Post date:** [April 23, 2019, 8:17pm UTC](https://discourse.pymc.io/t/correctly-applying-switchpoint-model/3143/3 "2019-04-23T20:17:39Z")

</div>

By the way, it’s possible to avoid MH while simultaneously adding some intuition that the change-point will be somewhere “in the middle” of the trend, by using a scaled Beta ( **nb** the hyperprior is enormously helpful for speeding up sampling):

```auto
with pm.Model() as switchpoint_model_noMH:
    # Scaled beta mixture "somewhere in the middle" prior
    a = pm.HalfNormal('a_hp', 3.)
    b = pm.HalfNormal('b_hp', 3.)
    sp_latent = pm.Beta('sp_latent', a, b)
    switchpoint = pm.Deterministic('switchpoint', X.min() + (X.max() - X.min()) * sp_latent)

    # Priors 
    beta1_offset = pm.Normal('beta1_offset')
    beta1 = pm.Deterministic("beta1", beta1_offset * 3)
 
    beta2_offset = pm.Normal('beta2_offset')
    beta2 = pm.Deterministic("beta2", beta2_offset * 3)
 
    intercept_offset = pm.Normal('intercept_offset', mu=0, sd=1)
    intercept = pm.Deterministic("intercept", intercept_offset * 3)

    std = pm.HalfNormal('std', sd=0.5)

    # Likelihood
    part1 = intercept + pm.math.dot(pm.math.sin(X), beta1)
         
    part2 = intercept + pm.math.dot(pm.math.sin(X), beta1) + \
                        pm.math.dot(pm.math.sqr(X), beta2)
         
    #model = pm.math.switch(tt.gt(switchpoint, X), part1, part2)
    w = tt.nnet.sigmoid(2*(X-switchpoint))
    model = (1-w)*part1 + w*part2

    y_lik = pm.Normal('y_lik', mu=model, sd=std, observed = Y)
    trace = pm.sample(1000, init='advi+adapt_diag', tune=tune + burn_in, chains=4, cores=3)
    ppc = pm.sample_posterior_predictive(trace, 1000)

```

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/1/188da14c22d9f239aa5f077476bc8c3d4e8378e5.png)

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/b/b2eac4534251c88a4cb4bac388da6ee07a966b05.png)
