Building the network and defining the cost functions