You only work on Tensor<T>, ILayer<T>, DenseLayer<T>, NeuralNetowrk<T>, Trainer<T>,…
- User
You only work on Tensor, ILayer, DenseLayer, NeuralNetowrk, Trainer, Evaluator based on best practices and academic knowledge in software engineering and numerical computing implement the following improvements, only generate new code or code changes, don't re-generate unchanged or old code and provide code copy paste explanation so I can avoid any copy paste errors and to avoid human confusion, implement the following improvements and fixs:
public partial class Tensor : IDisposable, ICloneable, IEquatable<Tensor>, IEnumerable where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { #region Fields and Properties internal readonly T[] data; private readonly int[] shape; private readonly int[] strides; private readonly int totalSize; private bool disposed = false; private readonly bool isRowMajor; private readonly int offset; public int[] Shape => (int[])shape.Clone(); public int TotalSize => totalSize; public static int ParallelizationThreshold { get; set; } = 1000; public int Rank => shape.Length; public T[] Data { get { EnsureNotDisposed(); return data; } } #endregion #region Constructors public Tensor(bool isRowMajor, params int[] dimensions) { if (dimensions == null || dimensions.Length == 0) throw new ArgumentException("Tensor must have at least one dimension.", nameof(dimensions)); foreach (var dim in dimensions) { if (dim <= 0) throw new ArgumentException("Each dimension size must be positive.", nameof(dimensions)); } shape = dimensions.ToArray(); this.isRowMajor = isRowMajor; strides = CalculateStrides(shape, isRowMajor); totalSize = strides[0] * shape[0]; data = ArrayPool.Shared.Rent(totalSize); Array.Clear(data, 0, totalSize); this.offset = 0; } private Tensor(T[] data, int[] shape, int[] strides, int totalSize, bool isRowMajor, bool disposed, int offset) { this.data = data; this.shape = shape; this.strides = strides; this.totalSize = totalSize; this.isRowMajor = isRowMajor; this.disposed = disposed; this.offset = offset; } public Tensor(params int[] dimensions) : this(true, dimensions) { } public Tensor(T scalarValue) { this.shape = new int[0]; this.strides = new int[0]; this.totalSize = 1; this.data = ArrayPool.Shared.Rent(1); this.data[0] = scalarValue; this.isRowMajor = true; this.offset = 0; } private Tensor(T[] data, int[] shape, int[] strides) : this(data, shape, strides, strides[0] * shape[0], true, false, 0) { } public Tensor(T[] dataArray, int[] dimensions) { if (dataArray == null) throw new ArgumentNullException(nameof(dataArray)); if (dimensions == null || dimensions.Length == 0) throw new ArgumentException("Tensor must have at least one dimension.", nameof(dimensions)); int totalSize = dimensions.Aggregate(1, (a, b) => a * b); if (dataArray.Length != totalSize) throw new ArgumentException("Data array size does not match tensor dimensions.", nameof(dataArray)); this.data = dataArray; this.shape = dimensions.ToArray(); this.strides = CalculateStrides(shape, isRowMajor: true); this.totalSize = totalSize; this.isRowMajor = true; this.offset = 0; } #endregion #region Indexer and Element Access public T this[params int[] indices] { get { EnsureNotDisposed(); int flatIndex = CalculateFlatIndex(indices); return data[flatIndex]; } set { EnsureNotDisposed(); int flatIndex = CalculateFlatIndex(indices); data[flatIndex] = value; } } #endregion #region Cloning and Equality public object Clone() { EnsureNotDisposed(); T[] newData = ArrayPool.Shared.Rent(totalSize); Array.Copy(data, offset, newData, 0, totalSize); int[] newShape = (int[])shape.Clone(); int[] newStrides = (int[])strides.Clone(); return new Tensor(newData, newShape, newStrides, totalSize, isRowMajor, disposed: false, offset: 0); } public bool Equals(Tensor? other) { EnsureNotDisposed(); if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (!shape.SequenceEqual(other.shape)) return false; for (int i = 0; i < totalSize; i++) { if (!data[offset + i].Equals(other.data[other.offset + i])) return false; } return true; } #endregion #region IEnumerable Implementation public IEnumerator GetEnumerator() { EnsureNotDisposed(); for (int i = 0; i < totalSize; i++) { yield return data[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Arithmetic Operations public static Tensor operator +(Tensor a, Tensor b) { return a.Add(b); } public static Tensor operator -(Tensor a, Tensor b) { return a.Subtract(b); } public static Tensor operator *(Tensor a, Tensor b) { return a.Multiply(b); } public static Tensor operator /(Tensor a, Tensor b) { return a.Divide(b); } public static Tensor operator +(Tensor a, T scalar) { return a.AddScalar(scalar); } public static Tensor operator +(T scalar, Tensor a) { return a.AddScalar(scalar); } public static Tensor operator -(Tensor a, T scalar) { return a.SubtractScalar(scalar); } public static Tensor operator -(T scalar, Tensor a) { return a.Negate().AddScalar(scalar); } public static Tensor operator *(Tensor a, T scalar) { return a.MultiplyScalar(scalar); } public static Tensor operator *(T scalar, Tensor a) { return a.MultiplyScalar(scalar); } public static Tensor operator /(Tensor a, T scalar) { return a.DivideScalar(scalar); } public static Tensor operator /(T scalar, Tensor a) { return a.Reciprocal().MultiplyScalar(scalar); } public Tensor Add(Tensor other) { return ElementWiseOperation(other, (x, y) => x + y); } public Tensor Subtract(Tensor other) { return ElementWiseOperation(other, (x, y) => x - y); } public Tensor Multiply(Tensor other) { return ElementWiseOperation(other, (x, y) => x * y); } public Tensor Divide(Tensor other) { return ElementWiseOperation(other, (x, y) => x / y); } public Tensor AddScalar(T scalar) { return ScalarOperation((x) => x + scalar); } public Tensor SubtractScalar(T scalar) { return ScalarOperation((x) => x - scalar); } public Tensor MultiplyScalar(T scalar) { return ScalarOperation((x) => x * scalar); } public Tensor DivideScalar(T scalar) { return ScalarOperation((x) => x / scalar); } public Tensor Negate() { return ScalarOperation((x) => -x); } public Tensor Reciprocal() { return ScalarOperation((x) => T.One / x); } public async Task<Tensor> AddAsync(Tensor other) { return await Task.Run(() => Add(other)); } public async Task<Tensor> SubtractAsync(Tensor other) { return await Task.Run(() => Subtract(other)); } public async Task<Tensor> MultiplyAsync(Tensor other) { return await Task.Run(() => Multiply(other)); } public async Task<Tensor> DivideAsync(Tensor other) { return await Task.Run(() => Divide(other)); } #region In Place Operations public void ElementWiseInPlaceOperation(Tensor other, Func<T, T, T> operation) { EnsureNotDisposed(); other.EnsureNotDisposed(); if (!this.shape.SequenceEqual(other.shape)) throw new ArgumentException("Number of slices ({slices.Length}) must match tensor rank ({rank})."); int[] newShape = new int[rank]; int[] newStrides = new int[rank]; int newTotalSize = 1; int newOffset = this.offset; for (int i = 0; i < rank; i++) { int dimSize = shape[i]; int stride = strides[i]; var (start, end, step) = slices[i]; int s = step ?? 1; if (s == 0) throw new ArgumentException("Slice step cannot be zero.", nameof(slices)); int begin = start.HasValue ? (start.Value >= 0 ? start.Value : dimSize + start.Value) : (s > 0 ? 0 : dimSize - 1); int stop = end.HasValue ? (end.Value >= 0 ? end.Value : dimSize + end.Value) : (s > 0 ? dimSize : -1); if (s > 0) { begin = Math.Max(begin, 0); stop = Math.Min(stop, dimSize); } else { begin = Math.Min(begin, dimSize - 1); stop = Math.Max(stop, -1); } if ((s > 0 && begin >= stop) || (s < 0 && begin <= stop)) { newShape[i] = 0; newStrides[i] = stride * s; continue; } int count = (int)Math.Ceiling((double)(stop - begin) / s); newShape[i] = count; newStrides[i] = stride * s; newOffset += begin * stride; newTotalSize *= count; } return new Tensor( data: this.data, shape: newShape, strides: newStrides, totalSize: newTotalSize, isRowMajor: this.isRowMajor, disposed: false, offset: newOffset ); } public void ClipInPlace(T minValue, T maxValue) { EnsureNotDisposed(); if (totalSize >= ParallelizationThreshold) { Parallel.For(0, totalSize, i => { if (data[i].CompareTo(minValue) < 0) data[i] = minValue; else if (data[i].CompareTo(maxValue) > 0) data[i] = maxValue; }); } else { for (int i = 0; i < totalSize; i++) { if (data[i].CompareTo(minValue) < 0) data[i] = minValue; else if (data[i].CompareTo(maxValue) > 0) data[i] = maxValue; } } } public Tensor Gather(int[] indices) { EnsureNotDisposed(); if (Rank == 0) throw new InvalidOperationException("Cannot gather from a scalar tensor."); int[] newShape = (int[])Shape.Clone(); newShape[0] = indices.Length; Tensor result = new Tensor(newShape); for (int i = 0; i < indices.Length; i++) { int sourceIndex = indices[i]; var slice = Slice(sourceIndex, 1).Squeeze(0); result.SetRow(i, slice); } return result; } public void SetRow(int rowIndex, Tensor rowTensor) { EnsureNotDisposed(); if (Rank < 2) throw new InvalidOperationException("SetRow requires at least a 2D tensor."); if (rowTensor.Rank != Rank - 1) throw new ArgumentException("Row tensor must have one less rank than the target tensor.", nameof(rowTensor)); if (!Shape.Skip(1).SequenceEqual(rowTensor.Shape)) throw new ArgumentException("Row tensor shape does not match.", nameof(rowTensor)); int rowSize = rowTensor.TotalSize; int destOffset = rowIndex * strides[0]; int sourceOffset = rowTensor.offset; Array.Copy(rowTensor.data, sourceOffset, data, destOffset, rowSize); } #endregion #region Advanced Operations public Tensor MatMul(Tensor other) { EnsureNotDisposed(); other.EnsureNotDisposed(); var aShape = this.shape; var bShape = other.shape; if (this.Rank == 1 && other.Rank == 1) { if (this.shape[0] != other.shape[0]) throw new ArgumentException("Shapes are not aligned for dot product."); T sum = T.Zero; for (int i = 0; i < this.shape[0]; i++) { sum += this[i] * other[i]; } var resultTensor = new Tensor(); resultTensor.data[0] = sum; return resultTensor; } if (this.Rank == 1) { var aReshaped = this.Reshape(1, this.shape[0]); var partialResult = aReshaped.MatMul(other); return partialResult.Reshape(partialResult.shape.Skip(1).ToArray()); } if (other.Rank == 1) { var bReshaped = other.Reshape(other.shape[0], 1); var partialResult = this.MatMul(bReshaped); return partialResult.Reshape(partialResult.shape.Take(this.Rank - 1).ToArray()); } int n = this.shape[this.Rank - 1]; int k = other.shape[other.Rank - 2]; if (n != k) throw new ArgumentException("Inner dimensions do not match for MatMul."); int[] aBatchShape = this.shape.Take(this.Rank - 2).ToArray(); int[] bBatchShape = other.shape.Take(other.Rank - 2).ToArray(); int[] resultBatchShape = BroadcastShapes(aBatchShape, bBatchShape); int m = this.shape[this.Rank - 2]; int p = other.shape[other.Rank - 1]; int[] resultShape = resultBatchShape.Concat(new int[] { m, p }).ToArray(); Tensor result = new Tensor(resultShape); var aStrides = this.strides; var bStrides = other.strides; var resultStrides = result.strides; int batchSize = resultBatchShape.Aggregate(1, (a, b) => a * b); if (batchSize >= ParallelizationThreshold) { Parallel.For(0, batchSize, batchIndex => { var batchIndices = UnflattenIndex(batchIndex, resultBatchShape); int aBatchOffset = GetBatchOffset(batchIndices, aBatchShape, aStrides); int bBatchOffset = GetBatchOffset(batchIndices, bBatchShape, bStrides); int resultBatchOffset = GetBatchOffset(batchIndices, resultBatchShape, resultStrides); for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { T sum = T.Zero; for (int l = 0; l < n; l++) { int aIndex = aBatchOffset + i * aStrides[this.Rank - 2] + l * aStrides[this.Rank - 1]; int bIndex = bBatchOffset + l * bStrides[other.Rank - 2] + j * bStrides[other.Rank - 1]; sum += this.data[aIndex] * other.data[bIndex]; } int resultIndex = resultBatchOffset + i * resultStrides[result.Rank - 2] + j * resultStrides[result.Rank - 1]; result.data[resultIndex] = sum; } } }); } else { for (int batchIndex = 0; batchIndex < batchSize; batchIndex++) { var batchIndices = UnflattenIndex(batchIndex, resultBatchShape); int aBatchOffset = GetBatchOffset(batchIndices, aBatchShape, aStrides); int bBatchOffset = GetBatchOffset(batchIndices, bBatchShape, bStrides); int resultBatchOffset = GetBatchOffset(batchIndices, resultBatchShape, resultStrides); for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { T sum = T.Zero; for (int l = 0; l < n; l++) { int aIndex = aBatchOffset + i * aStrides[this.Rank - 2] + l * aStrides[this.Rank - 1]; int bIndex = bBatchOffset + l * bStrides[other.Rank - 2] + j * bStrides[other.Rank - 1]; sum += this.data[aIndex] * other.data[bIndex]; } int resultIndex = resultBatchOffset + i * resultStrides[result.Rank - 2] + j * resultStrides[result.Rank - 1]; result.data[resultIndex] = sum; } } } } return result; } public Tensor Reshape(params int[] newShape) { EnsureNotDisposed(); int newTotalSize = 1; int unknownDimensionIndex = -1; for (int i = 0; i < newShape.Length; i++) { if (newShape[i] == -1) { if (unknownDimensionIndex != -1) throw new ArgumentException("Only one dimension can be set to -1.", nameof(newShape)); unknownDimensionIndex = i; } else if (newShape[i] <= 0) { throw new ArgumentException("Each dimension size must be positive, except for -1.", nameof(newShape)); } else { newTotalSize *= newShape[i]; } } if (unknownDimensionIndex != -1) { if (totalSize % newTotalSize != 0) throw new ArgumentException("The total size of new dimensions must be divisible by the total size of the tensor."); newShape[unknownDimensionIndex] = totalSize / newTotalSize; newTotalSize ', layerWidth) + "]"); } return sb.ToString(); } public class LayerInfo { public string LayerName { get; set; } public string LayerType { get; set; } public int NumInputs { get; set; } public int NumOutputs { get; set; } public string ActivationFunction { get; set; } } public List GetLayerInfo() { var layerInfoList = new List(); foreach (var layer in Layers) { layerInfoList.Add(new LayerInfo { LayerName = layer.Name, LayerType = layer.GetType().Name, NumInputs = layer.NumInputs, NumOutputs = layer.NumOutputs, ActivationFunction = layer.ActivationFunctionName }); } return layerInfoList; } } public class Trainer where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions, IMinMaxValue { public NeuralNetwork Network { get; private set; } public ILossFunction LossFunction { get; private set; } public IOptimizer Optimizer { get; private set; } public ILogger Logger { get; private set; } public int Epochs { get; set; } public int BatchSize { get; set; } public T GradientClippingThreshold { get; set; } = T.CreateChecked(1.0); public bool UseEarlyStopping { get; set; } = false; public int EarlyStoppingPatience { get; set; } = 5; public T BestValidationLoss { get; private set; } public int NoImprovementEpochs { get; private set; } public bool EnableCheckpointing { get; set; } = false; public string CheckpointDirectory { get; set; } = "checkpoints"; public int CheckpointInterval { get; set; } = 1; public event Action<int, int, T>? EpochCompleted; public event Action<int, int, T>? BatchCompleted; public Trainer( NeuralNetwork network, ILossFunction lossFunction, IOptimizer optimizer, ILogger logger, int epochs = 100, int batchSize = 32) { Network = network; LossFunction = lossFunction; Optimizer = optimizer; Logger = logger; Epochs = epochs; BatchSize = batchSize; BestValidationLoss = T.MaxValue; } public async Task TrainAsync( Tensor trainingData, Tensor trainingLabels, Tensor? validationData = null, Tensor? validationLabels = null, CancellationToken cancellationToken = default) { int numSamples = trainingData.Shape[0]; int totalBatches = (numSamples + BatchSize - 1) / BatchSize; Network.InitializeWeights(); for (int epoch = 0; epoch < Epochs; epoch++) { if (cancellationToken.IsCancellationRequested) { Logger.Log("Training cancelled.", LogLevel.Warning); break; } var epochStartTime = DateTime.UtcNow; ShuffleData(ref trainingData, ref trainingLabels); for (int batchIndex = 0; batchIndex < totalBatches; batchIndex++) { int batchStart = batchIndex * BatchSize; int currentBatchSize = Math.Min(BatchSize, numSamples - batchStart); var batchData = trainingData.Slice(batchStart, currentBatchSize); var batchLabels = trainingLabels.Slice(batchStart, currentBatchSize); var predictions = Network.Forward(batchData); T loss = LossFunction.ComputeLoss(predictions, batchLabels); var gradients = LossFunction.ComputeGradient(predictions, batchLabels); Backward(gradients); ClipGradients(); UpdateWeights(); ClearGradients(); BatchCompleted?.Invoke(epoch + 1, batchIndex + 1, loss); } T validationLoss = T.Zero; if (validationData != null && validationLabels != null) { validationLoss = Evaluate(validationData, validationLabels); Logger.Log("Epoch {epoch + 1} completed in {epochDuration.TotalSeconds:F2}s.", LogLevel.Info); } await Task.CompletedTask; } private void Backward(Tensor gradients) { var grad = gradients; for (int i = Network.Layers.Count - 1; i >= 0; i--) { grad = Network.Layers[i].Backward(grad); } } private void UpdateWeights() { foreach (var layer in Network.Layers) { layer.UpdateWeights(Optimizer); } } private void ClearGradients() { foreach (var layer in Network.Layers) { layer.ClearGradients(); } } private void ClipGradients() { foreach (var layer in Network.Layers) { foreach (var gradient in layer.GetGradients()) { gradient.ClipInPlace(-GradientClippingThreshold, GradientClippingThreshold); } } } private void ShuffleData(ref Tensor data, ref Tensor labels) { int numSamples = data.Shape[0]; var indices = Enumerable.Range(0, numSamples).OrderBy(x => Guid.NewGuid()).ToArray(); data = data.Gather(indices); labels = labels.Gather(indices); } public T Evaluate(Tensor data, Tensor labels) { var predictions = Network.Forward(data); T loss = LossFunction.ComputeLoss(predictions, labels); return loss; } private void SaveCheckpoint(int epoch, T validationLoss) { if (!Directory.Exists(CheckpointDirectory)) { Directory.CreateDirectory(CheckpointDirectory); } string checkpointPath = Path.Combine(CheckpointDirectory, "Checkpoint saved at '{checkpointPath}' with Validation Loss: {validationLoss}"); } public void LoadCheckpoint(string checkpointPath) { Network.Load(checkpointPath); Logger.Log("Evaluation Loss: {loss}"); return loss; } } public class SGDOptimizer : IOptimizer where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions{ public T LearningRate { get; set; } public SGDOptimizer(T learningRate) { this.LearningRate = learningRate; } public void Update(Tensor parameters, Tensor gradients) { var scaledGradients = gradients.MultiplyScalar(LearningRate); parameters.SubtractInPlace(scaledGradients); }}public class AdamOptimizer : IOptimizer where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions{ public T LearningRate { get; set; } private readonly T beta1; private readonly T beta2; private readonly T epsilon; private Dictionary<Tensor, (Tensor m, Tensor v, int t)> optimizerStates; public AdamOptimizer(T learningRate, T beta1, T beta2, T epsilon) { this.LearningRate = learningRate; this.beta1 = beta1; this.beta2 = beta2; this.epsilon = epsilon; optimizerStates = new Dictionary<Tensor, (Tensor, Tensor, int)>(); } public void Update(Tensor parameters, Tensor gradients) { if (!optimizerStates.ContainsKey(parameters)) { optimizerStates[parameters] = (Tensor.ZerosLike(parameters), Tensor.ZerosLike(parameters), 0); } var (m, v, t) = optimizerStates[parameters]; t += 1; m.MultiplyScalarInPlace(beta1); m.AddInPlace(gradients.MultiplyScalar(T.One - beta1)); v.MultiplyScalarInPlace(beta2); var gradSquared = gradients.Multiply(gradients); v.AddInPlace(gradSquared.MultiplyScalar(T.One - beta2)); T tAsT = T.CreateChecked(t); T oneMinusBeta1PowT = T.One - T.Pow(beta1, tAsT); T oneMinusBeta2PowT = T.One - T.Pow(beta2, tAsT); T biasCorrectedLearningRate = LearningRate * T.Sqrt(oneMinusBeta2PowT) / oneMinusBeta1PowT; var mHat = m.DivideScalar(oneMinusBeta1PowT); var vHat = v.DivideScalar(oneMinusBeta2PowT); var denom = vHat.ScalarOperation(x => T.Sqrt(x) + epsilon); var update = mHat.ElementWiseOperation(denom, (mh, vh) => mh / vh); parameters.SubtractInPlace(update.MultiplyScalar(biasCorrectedLearningRate)); optimizerStates[parameters] = (m, v, t); }} public class MeanSquaredError : ILossFunction where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { public T ComputeLoss(Tensor predicted, Tensor target) { var diff = predicted.Subtract(target); var squaredDiff = diff.Multiply(diff); return squaredDiff.Mean(); } public Tensor ComputeGradient(Tensor predicted, Tensor target) { var diff = predicted.Subtract(target); T scale = T.CreateChecked(2) / T.CreateChecked(predicted.TotalSize); return diff.MultiplyScalar(scale); } } public class CrossEntropyLoss : ILossFunction where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { public T ComputeLoss(Tensor predicted, Tensor target) { T epsilon = T.CreateChecked(1e-12); var logPredicted = predicted.ScalarOperation(x => T.Log(x + epsilon)); var losses = target.Multiply(logPredicted).Negate(); return losses.Mean(); } public Tensor ComputeGradient(Tensor predicted, Tensor target) { T scale = T.One / T.CreateChecked(predicted.TotalSize); return predicted.Subtract(target).MultiplyScalar(scale); } } public class L2Regularization : IRegularization where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions{ private readonly T lambda; public L2Regularization(T lambda) { this.lambda = lambda; } public T ComputePenalty(Tensor parameters) { var squared = parameters.Multiply(parameters); return squared.Sum() * (lambda / T.CreateChecked(2)); } public Tensor ComputeGradient(Tensor parameters) { return parameters.MultiplyScalar(lambda); }} public class RandomUniformInitializer : IInitializer where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { private readonly ThreadLocal => { double val = _threadLocalRng.Value.NextDouble(); return T.CreateChecked(val) * (max - min) + min; }); } } public class SoftmaxActivation : IActivationFunction where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { private int axis; private Tensor? lastOutput; public SoftmaxActivation(int axis = -1) { this.axis = axis; } public Tensor Forward(Tensor input) { int ndim = input.Shape.Length; int ax = axis < 0 ? ndim + axis : axis; var maxInput = input.Max(axis: ax); var maxInputExpanded = maxInput.ExpandDims(ax); var shiftedInput = input.Subtract(maxInputExpanded); var expShifted = shiftedInput.ScalarOperation(x => T.Exp(x)); var sumExp = expShifted.Sum(axis: ax); var sumExpExpanded = sumExp.ExpandDims(ax); lastOutput = expShifted.Divide(sumExpExpanded); return lastOutput; } public Tensor Backward(Tensor input, Tensor gradOutput) { if (lastOutput == null) throw new InvalidOperationException("Forward must be called before Backward."); int ndim = input.Shape.Length; int ax = axis < 0 ? ndim + axis : axis; var dotProduct = lastOutput.Multiply(gradOutput).Sum(axis: ax); dotProduct = dotProduct.ExpandDims(ax); var gradDifference = gradOutput.Subtract(dotProduct); var gradInput = lastOutput.Multiply(gradDifference); return gradInput; } } public class ReLUActivation : IActivationFunction where T : unmanaged, INumber, IExponentialFunctions, ITrigonometricFunctions, ILogarithmicFunctions, IFloatingPointIeee754, IRootFunctions { public Tensor Forward(Tensor input) { return input.ScalarOperation(x => T.Max(x, T.Zero)); } public Tensor Backward(Tensor input, Tensor gradOutput) { return input.ElementWiseOperation(gradOutput, (x, grad) => x > T.Zero ? grad : T.Zero); } }
- Assistant