<commit_before><commit_msg>Added helper class for linear regression.<commit_after>/*
 * (c) Copyright <NAME>, Germany. Contact: <EMAIL>.
 *
 * Created on 26.08.2018
 */
package net.finmath.montecarlo.conditionalexpectation;

import net.finmath.functions.LinearAlgebra;
import net.finmath.stochastic.RandomVariableInterface;

public class LinearRegression {

	private final RandomVariableInterface[] basisFunctions;

	/**
	 * Create the linear regression with a set of basis functions.
	 * 
	 * @param basisFunctions A vector of (independent) random variables to be used as basis functions.
	 */
	public LinearRegression(RandomVariableInterface[] basisFunctions) {
		super();
		this.basisFunctions = basisFunctions;
	}

	/**
	 * Get the vector of regression coefficients.
	 * 
	 * @param value The random variable to regress.
	 * @return The vector of regression coefficients.
	 */
	public double[] getRegressionCoefficients(RandomVariableInterface value) {
		// Build regression matrix
		double[][] BTB = new double[basisFunctions.length][basisFunctions.length];
		for(int i=0; i<basisFunctions.length; i++) {
			for(int j=0; j<=i; j++) {
				double covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();
				BTB[i][j] = covariance;
				BTB[j][i] = covariance;
			}
		}

		double[] BTX = new double[basisFunctions.length];
		for(int i=0; i<basisFunctions.length; i++) {
			double covariance = basisFunctions[i].mult(value).getAverage();
			BTX[i] = covariance;
		}

		return LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);
	}
}
{'fraction_non_alphanumeric': 0.11943189154293092, 'fraction_numerical': 0.0071013557133634605, 'mean_word_length': 4.636363636363637, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1698104', 'n_tokens_mistral': 528, 'n_tokens_neox': 446, 'n_words': 119}