# Load part model with pretrained weights; other part reinit xavier

**URL:** <https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310>\
**Category:** Uncategorized\
**Created:** [March 31, 2019, 12:05pm UTC](https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310 "2019-03-31T12:05:42Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![a-parida12](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/a-parida12/32/10028_2.png) [@a-parida12](https://discuss.pytorch.org/u/a-parida12)\
**Post date:** [March 31, 2019, 12:05pm UTC](https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310/1 "2019-03-31T12:05:42Z")

</div>

Currently I load a pretrained 7 layered network model using the command.

> myNet=torch.load(‘path\_to\_model’)

Now I want to retrain the pretrained weights in the first 5 layer and re initialize the last two layers to xavier init or any initialisation.

How is possible for me to do so?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [March 31, 2019, 12:16pm UTC](https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310/2 "2019-03-31T12:16:22Z")

</div>

You could load the pretrained weights and just call the desired init method on the last two layers:

```python
model = ...
model.load_state_dict(torch.load(...)) # or your equivalent code using torch.load
with torch.no_grad():
    torch.nn.init.xavier_uniform_(model.fc1.weight)
    torch.nn.init.zeros_(model.fc1.bias)
    ...

```

---

<div class="post-metadata">

**Author:** ![a-parida12](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/a-parida12/32/10028_2.png) [@a-parida12](https://discuss.pytorch.org/u/a-parida12)\
**Post date:** [March 31, 2019, 12:20pm UTC](https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310/3 "2019-03-31T12:20:41Z")

</div>

okay got it. but can you tell me why we would need the `torch.no_grad()` here?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [March 31, 2019, 12:22pm UTC](https://discuss.pytorch.org/t/load-part-model-with-pretrained-weights-other-part-reinit-xavier/41310/4 "2019-03-31T12:22:27Z")

</div>

In the posted code snippet you won’t really need it.  
It was just a security measure in case you performed some operations before loading the weights, so in case you initialize the parameters right after loading the model, you can just remove it.
