# [PYTHON] Save the pystan model and results in a pickle file

## What to do in this article

--Save the model and result created using pystan as a pickle file
--Introducing how to read the model and result without recalculating

## Conclusion

`python`

```
#writing
with open('model.pkl', 'wb') as f:
pickle.dump(stm, f)
with open('fit.pkl', 'wb') as g:
pickle.dump(fit, g)
#Read
stm = pickle.load(open(DATA_DIR + 'model_ForS.pkl', 'rb'))
fit = pickle.load(open(DATA_DIR + 'fit_ForS.pkl', 'rb'))
```

## The problem you want to solve

Bayesian statistical modeling by pystan is convenient, but it takes a lot of calculation method. It depends on the item, but most of them take about an hour. Moreover, it is often the case that the calculation did not converge.

So many people want to save the calculated result. It may be written in the tutorial book, but I think that there are many people who say ** because there are many Rstan books, without knowing how to save python **.

So in this article
-** Save the model and results of Bayesian statistical modeling by pystan in a pickle file **
I will show you how.

## Solution

Suppose you compile and sample with pystan as follows.
Here, the model is stored in stm and the sampling result is stored in fit.

`python`

```
model = """
data{
...
}
parameters{
...
}
model{
...
}
"""
stm = pystan.StanModel(model_code=model) #compile
stan_data = {...}
fit = stm.sampling(data=stan_data) #sampling
```

At this time, you can save and write by writing as follows. It was easy.
Even if only the result is saved, it cannot be read.
You have to save the model with it.
I don't know the details, but it seems that the sampling result is linked to the model.

`python`

```
#writing
with open('model.pkl', 'wb') as f:
pickle.dump(stm, f)
with open('fit.pkl', 'wb') as g:
pickle.dump(fit, g)
#Read
stm = pickle.load(open(DATA_DIR + 'model_ForS.pkl', 'rb'))
fit = pickle.load(open(DATA_DIR + 'fit_ForS.pkl', 'rb'))
```