# Custom function in Neural Network Layer

I am trying to create a custom function in a Neural Network. The output of the NN is a n x 2 matrix which represent coordinates of points in a plane. From this, the Euclidean pairwise distance matrix needs to be computed which is then compared with the target pairwise distance matrix. Here is what I have so far:

coords1 = N@ Round[RandomReal[{-10., 10}, {5, 2}], 10^-4];

distM = Table[Table[EuclideanDistance[pi, pj], {pj, coords1}], {pi, coords1}] // MatrixForm; (* Distance Matrix *)

(* Pure function that computes the distance matrix *)
func = (Partition[#, Sqrt@Length@#] &)@*
Map[EuclideanDistance[#[], #[]] &]@*
(Partition[Part[#, Join @@ Tuples[{Range@Length@#, Range@Length@#}]], 2] &

(* The last Linear Layer 5 x 5 should be replaced by a layer that uses the above custom function to compute the distance matrix *)
net = NetChain[{LinearLayer[{5, 2}], ElementwiseLayer[Ramp], LinearLayer[{5, 5}]}, "Input" -> {5, 2}, "Output" -> {5, 5} ]


Any ideas? I have reviewed the documentation and I could not find anything that I could use. I appreciate any help in this matter.

Thanks

• What have you tried so far? Are you trying to define a single layer to perform all of these steps? – CA Trevillian Aug 10 '20 at 8:28

I was able to solve the problem that I had using the following code:

    net2 = NetGraph[{PartLayer[{All, 1}], PartLayer[{All, 2}],
ReplicateLayer[5, 1], ReplicateLayer[5, 2],
ReplicateLayer[5, 1], ReplicateLayer[5, 2],