2
$\begingroup$

Is there a way that I can achieve subtraction between a scalar and a vector within NetGraph[], similar to what happens when I perform {1, 2, 3}-1 to get {0,1,2}? For my purposes, this needs to be done within NetGraph[] for timing and functional reasons. Part of the trouble is that the vector also will be changing in size. Is there already a NetGraph[] layer that has these functionalities?

For those who want a little more background, I am trying to create a filter within my network as part of the loss function, where the data being fed into the network spans over just two days and each day (of the week) is represented as a value between 0 and 1. So Monday is represented as 0.0 and Tuesday as 0.2 and so forth.

I am using SequenceLastLayer[] to get the time of the last bar of data, and am attempting to use this in conjunction with a slightly modified Tanh[] function within ThreadingLayer[], as well as the bars with the other time values whose form will be similar to {.0,.0,.0,...,.2,.2,.2,}. So the one scalar, in this example, would be 0.2 and the vector would be {.0,.0,.0,...,.2,.2,.2,}, and the operation would be:

`{.0,.0,.0,...,.2,.2,.2,} - 0.2`

This seems like it should be relatively simple, but I have not yet been able to figure it out. Does anyone know what I can do differently?

Here is the code so far:

net = NetGraph[<|"thread" -> ThreadingLayer[#1*#2 &], 
   "getLastLayer" -> 
    SequenceLastLayer[]|>, {NetPort["timeInput"] -> {"getLastLayer", 
     "thread"}, "getLastLayer" -> "thread"}]

enter image description here

And the code to run it would be similar to:

net[<|"timeInput" -> {0.0,0.0,0.0,...,0.2,0.2,0.2,}|>]
$\endgroup$
2
$\begingroup$

This can be achieved with ReplicateLayer:

subtractionLayer = NetGraph[
  {ReplicateLayer[Automatic], ThreadingLayer[#1 - #2 &]},
  {NetPort["Scalar"] -> 1, {NetPort["Vector"], 1} -> 2}
  ];
subtractionLayer[<|"Vector" -> {1, 2, 3}, "Scalar" -> 1|>]
(* {0., 1., 2.} *)

The "scalar" can also be an array with one less dimensions than the "vector":

subtractionLayer[<|"Vector" -> {{1, 1}, {2, 2}, {3, 3}}, "Scalar" -> {0, 1}|>]
(* {{1., 0.}, {2., 1.}, {3., 2.}} *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks! This is just what I was looking for. $\endgroup$ – Jmeeks29ig Jan 15 at 3:55
  • $\begingroup$ You're welcome! $\endgroup$ – aooiiii Jan 15 at 3:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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