Tensor<T> constructor

Tensor<T>(
  1. dynamic initialValue, {
  2. Node? creator,
})

Implementation

Tensor(dynamic initialValue, {this.creator}) {
  id = 't_$_idCounter';
  _idCounter = _idCounter + 1;

  if (initialValue is double) {
    shape = [];
  } else if (initialValue is List<double>) {
    shape = [initialValue.length];
  } else if (initialValue is List<List<double>>) {
    int rows = initialValue.length;
    int cols = rows > 0 ? initialValue[0].length : 0;
    shape = [rows, cols];
  } else if (initialValue is List<List<List<double>>>) {
    int depth  = initialValue.length;
    int height = depth > 0 ? initialValue[0].length : 0;
    int width  = height > 0 ? initialValue[0][0].length : 0;
    shape = [depth, height, width];
  } else {
    throw Exception("Unsupported tensor initialization type.");
  }

  int numElements = _elementCount(shape);

  dataPtr = calloc<Float>(numElements);
  data    = dataPtr.asTypedList(numElements);
  gradPtr = calloc<Float>(numElements);
  grad    = gradPtr.asTypedList(numElements);

  if (initialValue is double) {
    data[0] = initialValue;
  } else if (initialValue is List<double>) {
    for (int i = 0; i < initialValue.length; i = i + 1) {
      data[i] = initialValue[i];
    }
  } else if (initialValue is List<List<double>>) {
    int cols = shape[1];
    for (int i = 0; i < initialValue.length; i = i + 1) {
      for (int j = 0; j < initialValue[i].length; j = j + 1) {
        data[(i * cols) + j] = initialValue[i][j];
      }
    }
  } else if (initialValue is List<List<List<double>>>) {
    int height = shape[1];
    int width  = shape[2];
    for (int d = 0; d < initialValue.length; d = d + 1) {
      for (int h = 0; h < initialValue[d].length; h = h + 1) {
        for (int w = 0; w < initialValue[d][h].length; w = w + 1) {
          data[(d * height * width) + (h * width) + w] = initialValue[d][h][w];
        }
      }
    }
  }
}