使用 tf.conv2d 添加偏差 - Tensorflow.js

Add bias with tf.conv2d - Tensorflow.js

请注意,它不是 tf.layers.conv2d,请参阅 reference

我找不到可以作为卷积偏差传递的参数。参见示例:

//(3x3x3)
const images = tf.tensor([
  //image
  [
    //height
    [[255,255,255],[55,55,55],[0,0,0]], //width
    [[255,255,255],[55,55,55],[0,0,0]],
    [[255,255,255],[55,55,55],[0,0,0]],
  ],
  //image
  [
    //height
    [[255,255,255],[55,55,55],[0,0,0]], //width
    [[255,255,255],[55,55,55],[0,0,0]],
    [[255,255,255],[55,55,55],[0,0,0]],
  ]
]);

//(2x2x2)
const filters = tf.tensor(
  [ //height
    [ //width
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
    ],
    [ //width
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
    ]
  ]
)

const stride = 1;

images.conv2d(filters, stride, 0).print()
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>

效果很好,但是,NHWC 格式确实让我感到困惑,尤其是在使用过滤器时,无法使用过滤器将它们设置为 NCHW,只能输入,但主要问题是我找不到添加偏差的方法每出深度。有什么办法或解决方法吗?

根据 documentation,数据格式可以作为参数传递给 tf.conv2d。另外添加偏差 tf.add 可以如下所示使用:

//(3x3x3)
const images = tf.tensor([
  //image
  [
    //height
    [[255,255,255],[55,55,55],[0,0,0]], //width
    [[255,255,255],[55,55,55],[0,0,0]],
    [[255,255,255],[55,55,55],[0,0,0]],
  ],
  //image
  [
    //height
    [[255,255,255],[55,55,55],[0,0,0]], //width
    [[255,255,255],[55,55,55],[0,0,0]],
    [[255,255,255],[55,55,55],[0,0,0]],
  ]
]);

//(2x2x2)
const filters = tf.tensor(
  [ //height
    [ //width
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
    ],
    [ //width
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
      [ //pixel, prevdepth
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
        [ //nextdepth
          0, 3
        ],
      ],
    ]
  ]
)

const stride = 1;

conv = images.conv2d(filters, stride, 0, 'NCHW')
add = conv.add([2, 3])
add.print()
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>