/// <summary> /// Applies matrix dot product operation for /// all matrices in tensors /// /// O(N^3) /// </summary> public static GenTensor <T> TensorMatrixMultiply(GenTensor <T> a, GenTensor <T> b) { #if ALLOW_EXCEPTIONS if (a.Shape.Count < 2 || b.Shape.Count < 2) { throw new InvalidShapeException($"Arguments should be at least matrices while their shapes are {a.Shape} and {b.Shape}"); } if (a.Shape.SubShape(0, 2) != b.Shape.SubShape(0, 2)) { throw new InvalidShapeException("Other dimensions of tensors should be equal"); } #endif var oldShape = a.Shape.SubShape(0, 2).ToArray(); var newShape = new int[oldShape.Length + 2]; for (int i = 0; i < oldShape.Length; i++) { newShape[i] = oldShape[i]; } newShape[newShape.Length - 2] = a.Shape[a.Shape.Length - 2]; newShape[newShape.Length - 1] = b.Shape[b.Shape.Length - 1]; var resTensor = new GenTensor <T>(newShape); foreach (var subDimensions in a.IterateOverMatrices()) { var product = MatrixMultiply(a.GetSubtensor(subDimensions), b.GetSubtensor(subDimensions)); resTensor.SetSubtensor(product, subDimensions); } return(resTensor); }
/// <summary> /// Creates a tensor whose all matrices are identity matrices /// 1 is achieved with TWrapper.SetOne() /// 0 is achieved with TWrapper.SetZero() /// </summary> public static GenTensor <T> CreateIdentityTensor(int[] dimensions, int finalMatrixDiag) { var newDims = new int[dimensions.Length + 2]; for (int i = 0; i < dimensions.Length; i++) { newDims[i] = dimensions[i]; } newDims[newDims.Length - 2] = newDims[newDims.Length - 1] = finalMatrixDiag; var res = new GenTensor <T>(newDims); foreach (var index in res.IterateOverMatrices()) { var iden = CreateIdentityMatrix(finalMatrixDiag); res.SetSubtensor(iden, index); } return(res); }
public static GenTensor <T> TensorMatrixDivide(GenTensor <T> a, GenTensor <T> b) { #if ALLOW_EXCEPTIONS InvalidShapeException.NeedTensorSquareMatrix(a); InvalidShapeException.NeedTensorSquareMatrix(b); if (a.Shape != b.Shape) { throw new InvalidShapeException("Should be of the same shape"); } #endif var res = new GenTensor <T>(a.Shape); foreach (var ind in res.IterateOverMatrices()) { res.SetSubtensor( MatrixDivide( a.GetSubtensor(ind), b.GetSubtensor(ind) ), ind); } return(res); }