Mathematica Asked on May 9, 2021
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
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
Answered by Chris on May 9, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP