# Function for creating a neural network with n hidden layers in Flux

**URL:** <https://discourse.julialang.org/t/function-for-creating-a-neural-network-with-n-hidden-layers-in-flux/75589>\
**Category:** Machine Learning\
**Created:** [February 1, 2022, 5:27pm UTC](https://discourse.julialang.org/t/function-for-creating-a-neural-network-with-n-hidden-layers-in-flux/75589 "2022-02-01T17:27:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Handam](https://avatars.discourse-cdn.com/v4/letter/h/ccd318/32.png) [@Handam](https://discourse.julialang.org/u/Handam)\
**Post date:** [February 1, 2022, 5:27pm UTC](https://discourse.julialang.org/t/function-for-creating-a-neural-network-with-n-hidden-layers-in-flux/75589/1 "2022-02-01T17:27:24Z")

</div>

Hi,

I want to create a function, where I can set the number of hidden layers with an argument. One option that kinda works is

```julia
using Flux
function make_nn(length_in = 80, length_out = 1, nodes = 128, hid_lay = 3, act_fun = relu, act_fun_last = sigmoid)
	q = Dense(length_in, nodes, act_fun)
	for i in 1:hid_lay-1
		q = Chain(q, Dense(nodes, nodes, act_fun))
	end
	q = Chain(q, Dense(nodes, length_out, act_fun_last))
end

```

but the output is a nested Chain which is not particular beautiful to me:

```julia
Chain(
  Chain(
    Chain(
      Dense(80, 128, relu), # 10_368 parameters
      Dense(128, 128, relu), # 16_512 parameters
    ),
    Dense(128, 128, relu), # 16_512 parameters
  ),
  Dense(128, 1, σ), # 129 parameters
)     

```

Is there a better way to do this in Flux?

Best regards.

---

<div class="post-metadata">

**Author:** ![vimo](https://avatars.discourse-cdn.com/v4/letter/v/5f9b8f/32.png) [@vimo](https://discourse.julialang.org/u/vimo)\
**Post date:** [February 1, 2022, 6:08pm UTC](https://discourse.julialang.org/t/function-for-creating-a-neural-network-with-n-hidden-layers-in-flux/75589/2 "2022-02-01T18:08:18Z")

</div>

You could create the layers first and then stack them, something like this maybe

```julia
using Flux

function make_nn(length_in = 80, length_out = 1, nodes = 128, hid_lay = 3, act_fun = relu, act_fun_last = sigmoid)
	first_layer = Dense(length_in, nodes, act_fun)
    intermediate_layers = [Dense(nodes,nodes,act_fun) for _ in 1:hid_lay-1]
    last_layer = Dense(nodes, length_out, act_fun_last)

	return Chain(
        first_layer,
        intermediate_layers...,
        last_layer
    )
end

```
