0
$\begingroup$

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[#[[1]], #[[2]]] &]@*
            (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

$\endgroup$
1
  • $\begingroup$ What have you tried so far? Are you trying to define a single layer to perform all of these steps? $\endgroup$ Commented Aug 10, 2020 at 8:28

1 Answer 1

1
$\begingroup$

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],   
                     ThreadingLayer[Subtract], ThreadingLayer[Subtract],  
                     ThreadingLayer[#^2 &], 
                     ThreadingLayer[#^2 &], ThreadingLayer[Plus], 
                     ThreadingLayer[Sqrt[#] &]}, 
                     { 1 -> 3, 2 -> 5, 1 -> 4, 2 -> 6, {3, 4} -> 7, 
                      {5, 6} -> 8, 7 -> 9, 8 -> 10, {9, 10} -> 11, 11 -> 12}];

net2[coords1] // MatrixForm
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.