FastPrepMulti-Channel Valid Convolution

Multi-Channel Valid Convolution

Tesla logoTesla● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Implement a multi-channel two-dimensional convolution using direct loops.

The input tensor input has shape [channels][height][width]. There are filters convolution kernels. To fit the callable interface, kernels[f] stores filter f as one channel-major flattened row. The value for channel c, kernel row r, and kernel column k is at index c * kernelHeight * kernelWidth + r * kernelWidth + k.

Use stride 1, no padding, and the cross-correlation convention used by neural-network layers: do not reverse the kernel. Do not add a bias or apply an activation function.

Return a tensor of shape [filters][height - kernelHeight + 1][width - kernelWidth + 1]. Each output value is the sum, over every input channel and kernel position, of the corresponding input value multiplied by its kernel value.

Function

convolveValid(input: int[][][], kernels: int[][], kernelHeight: int, kernelWidth: int) → int[][][]

Examples

Example 1

input = [[[1,2,3],[4,5,6],[7,8,9]]]kernels = [[1,0,0,-1]]kernelHeight = 2kernelWidth = 2return = [[[-4,-4],[-4,-4]]]

There is one channel and one 2 x 2 filter. At the top-left position, the sum is 1 * 1 + 2 * 0 + 4 * 0 + 5 * (-1) = -4. The same difference appears at every valid position.

Example 2

input = [[[1,2],[3,4]],[[5,6],[7,8]]]kernels = [[1,0,0,1,0,1,1,0]]kernelHeight = 2kernelWidth = 2return = [[[18]]]

The first channel contributes 1 + 4 = 5, and the second contributes 6 + 7 = 13, for a total of 18.

Example 3

input = [[[1,2,3],[4,5,6]]]kernels = [[1,1],[1,-1]]kernelHeight = 1kernelWidth = 2return = [[[3,5],[9,11]],[[-1,-1],[-1,-1]]]

The first filter adds adjacent values. The second subtracts the second value in each window from the first.

Constraints

  • 1 <= channels <= 8.
  • 1 <= height, width <= 20.
  • 1 <= filters <= 8.
  • 1 <= kernelHeight <= height and 1 <= kernelWidth <= width.
  • kernels.length == filters.
  • Every row of kernels has length channels * kernelHeight * kernelWidth.
  • All input and kernel values are between -100 and 100, inclusive.
  • Every output value fits in a signed 32-bit integer.

More Tesla problems

See Tesla hiring insights
public int[][][] convolveValid(int[][][] input, int[][] kernels, int kernelHeight, int kernelWidth) {
  // write your code here
}
input[[[1,2,3],[4,5,6],[7,8,9]]]
kernels[[1,0,0,-1]]
kernelHeight2
kernelWidth2
expected[[[-4,-4],[-4,-4]]]
Checking account…