The key here is that a system will tend towards the lowest energy state; in other words, for a process to be spontaneous, the final state must have lower energy than the initial state.
The mass of a neutron is slightly higher than the combined mass of the proton, electron and neutrino that result from beta decay, meaning that the decay will be energetically favoured. This might be easier to understand by considering the decay of a free neutron:
$$\text{n}^0 \rightarrow \text{p}^+ + \text{e}^-+\bar{\nu}_\text{e}$$
Whether this process will occur in a nuclear neutron is determined by the $N/Z$ ratio and the atomic number. In small neutron-rich nuclei, the process above will predominate, but as the nucleus gets larger, more neutrons are needed to counteract the electromagnetic repulsion between protons (which has a longer range than the strong nuclear force). Again, the reason is energy: the unbound nuclei collectively have higher energy than a nucleus, due to nuclear binding energy. Hence, for larger nuclei, neutron decay is not energetically favourable.