# Training gets differents results when using Flux.train() inside function

**URL:** https://discourse.julialang.org/t/training-gets-differents-results-when-using-flux-train-inside-function/45284
**Category:** Machine Learning
**Tags:** flux
**Created:** [August 20, 2020, 7:52pm UTC](https://discourse.julialang.org/t/training-gets-differents-results-when-using-flux-train-inside-function/45284 "2020-08-20T19:52:34Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![darsnack](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/darsnack/32/10144_2.png) [@darsnack](https://discourse.julialang.org/u/darsnack)
#### Post date: [August 20, 2020, 8:44pm UTC](https://discourse.julialang.org/t/training-gets-differents-results-when-using-flux-train-inside-function/45284/2 "2020-08-20T20:44:19Z")

</div>

Probably has to do with your `loss(x, y)` definition. I suspect the `m` in the function body is not referencing the `m` created inside `all_the_code` and instead referencing some other `m` in global scope. In any case, it is better to explicitly pass in the model to the `loss` function, because depending on the scoping of `m`, you maybe using a global variable which can cause performance issues (and bugs like this one!). Instead you should define

```julia
loss(x, y, m) = Flux.mse(m(x), y)

```

then when you call `train!`, you can use a closure over `m`:

```julia
Flux.train!((x, y) -> loss(x, y, m), ps, datatrain, opt, cb = throttle(evalcb, time_show))

```

This will close over the `m` in the same scope as where `Flux.train!` was called, so unless you do something really weird, it should be referencing the `m` you expect.

---

_[View the full topic](https://discourse.julialang.org/t/training-gets-differents-results-when-using-flux-train-inside-function/45284)._
