本文整理汇总了C#中MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.SetRow方法的典型用法代码示例。如果您正苦于以下问题:C# DenseMatrix.SetRow方法的具体用法?C# DenseMatrix.SetRow怎么用?C# DenseMatrix.SetRow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MathNet.Numerics.LinearAlgebra.Double.DenseMatrix
的用法示例。
在下文中一共展示了DenseMatrix.SetRow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: build_prob_map
public void build_prob_map()
{
Normal N_x = new Normal(X / 2, STD_X);
Normal N_y = new Normal(Y / 2, STD_Y);
DenseMatrix M_x = new DenseMatrix(Y, X, 0.0);
DenseMatrix M_y = new DenseMatrix(Y, X, 0.0);
DenseVector V_x = new DenseVector(X);
for (int i = 0; i < X; i++)
{
V_x[i] = N_x.Density(i);
}
for (int j = 0; j < Y; j++)
{
M_x.SetRow(j, V_x);
}
DenseVector V_y = new DenseVector(Y);
for (int i = 0; i < Y; i++)
{
V_y[i] = N_y.Density(i);
}
for (int j = 0; j < X; j++)
{
M_y.SetColumn(j, V_y);
}
DenseMatrix MULT = (DenseMatrix)M_x.PointwiseMultiply(M_y);
double s = MULT.Data.Sum();
MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(Y, X, s));
//this.dataGridView1.DataSource = MULT;
//Console.WriteLine(MULT.Data.Sum());
PROB_MAP_ORIG = MULT;
s = MULT[Y / 2, X / 2];
MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(Y, X, s));
/*
for (int i = 0; i < Y; i++)
{
Console.Write(i + " - ");
for (int j = 0; j < X; j++)
{
Console.Write(MULT[i, j] + " ");
}
Console.WriteLine();
Console.WriteLine();
}
*/
PROB_MAP = MULT;
}
示例2: PrepareMatrices
private void PrepareMatrices(ArrayList kinectCoors, ArrayList projectorCoors)
{
foundCoordinatesMatrix = new DenseMatrix(projectorCoors.Count * 2, 11);
rightSideMatrix = new DenseMatrix(projectorCoors.Count * 2, 1);
for (int i = 0; i < projectorCoors.Count; i = i + 2)
{
Point3D kc = (Point3D) kinectCoors[i / 2];
Point2D projC = (Point2D) projectorCoors[i / 2];
double[] valueArray = new double[] {kc.X, kc.Y, kc.Z, 1, 0, 0, 0, 0, -projC.X * kc.X, -projC.X * kc.Y, -projC.X * kc.Z};
Vector<double> values = Vector<double>.Build.Dense(valueArray);
foundCoordinatesMatrix.SetRow(i, values);
Vector<double> rightSide = Vector<double>.Build.Dense(1, projC.X);
rightSideMatrix.SetRow(i, rightSide);
valueArray = new double[] {0, 0, 0, 0, kc.X, kc.Y, kc.Z, 1, -projC.Y * kc.X, -projC.Y * kc.Y, -projC.Y * kc.Z};
values = Vector<double>.Build.Dense(valueArray);
foundCoordinatesMatrix.SetRow(i + 1, values);
rightSide = Vector<double>.Build.Dense(1, projC.Y);
rightSideMatrix.SetRow(i + 1, rightSide);
}
}
示例3: NormalizeData
public DenseMatrix NormalizeData(DenseMatrix data)
{
var normalizedData = new DenseMatrix(data.RowCount, data.ColumnCount);
for (int i = 0; i < data.RowCount; i++)
{
normalizedData.SetRow(i, normalizeArrayInput[i].Process(data.Row(i).ToArray()));
}
return normalizedData;
}
示例4: Smooth
public void Smooth(ref double[,] inputValues)
{
// TODO: Using the matrix works, but does a lot of data accesses. Can improve by working out all the data access myself? I might be able to cut down on number of data accesses, but not sure.
var inputMatrix = new DenseMatrix(inputValues.GetLength(0), inputValues.GetLength(1));
for (int i = 0; i < inputMatrix.RowCount; i++)
{
inputMatrix.SetRow(i, Smooth(inputMatrix.Row(i).ToArray()));
}
for (int i = 0; i < inputMatrix.ColumnCount; i++)
{
inputMatrix.SetColumn(i, Smooth(inputMatrix.Column(i).ToArray()));
}
inputValues = inputMatrix.ToArray();
}
示例5: Process
public static void Process(FXSession session, string symbol1, string symbol2, string timeframe, int length)
{
HistoricPriceEngine h1 = new HistoricPriceEngine(session);
h1.GetLongHistoricPrices(symbol1, timeframe, length);
while (!h1.Complete)
{
Thread.Sleep(100);
}
HistoricPriceEngine h2 = new HistoricPriceEngine(session);
h2.GetLongHistoricPrices(symbol2, timeframe, length);
while (!h2.Complete)
{
Thread.Sleep(100);
}
//-----------------------
var dateTimeList = new SortedList<DateTime, int>();
Quantum q1 = h1.Data;
Quantum q2 = h2.Data;
var priceData = new DenseMatrix(2, q1.Data.Count);
for (int j = 0; j < ((q1.Data.Count <= q2.Data.Count)?q1.Data.Count:q2.Data.Count); j++ )
{
dateTimeList.Add(q1.Data.Values[j].Time, 1);
priceData[0, j] = q1.Data.Values[j].BidClose;
priceData[1, j] = q2.Data.Values[j].BidClose;
}
Vector<double> price1 = priceData.Row(0);
Vector<double> price2 = priceData.Row(1);
//Statistics.ApplyFunction((DenseVector)price1, Math.Log);
//Statistics.ApplyFunction((DenseVector)price2, Math.Log);
DenseVector norm1 = price1.ToArray().NormalizeZScore();
DenseVector norm2 = price2.ToArray().NormalizeZScore();
var newsym = new string[] {symbol1, symbol2, "spread"};
var m = new DenseMatrix(6, norm1.Count);
m.SetRow(0, norm1);
m.SetRow(1, norm2);
m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());
string filename = symbol1.Replace('/', '_') + "-" + symbol2.Replace('/', '_') + ".html";
Visualize.GenerateMultiPaneGraph(newsym, dateTimeList.Keys.ToArray(), m, QSConstants.DEFAULT_DATA_FILEPATH + filename,
new ChartOption[]{new ChartOption(), new ChartOption(){Layover = true, YPosition = 0}, new ChartOption(){YPosition = 1} }, null, filename + ".json");
FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename, filename);
FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename + ".json", filename + ".json");
double Spread = m[2, m.ColumnCount - 1];
if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Above 2.0", "Test");
if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Below -2.0", "Test");
}
示例6: createMatrix
public DenseMatrix createMatrix(Model model)
{
int numConstraints = model.Constraints.Count;
int numDecisionVars = model.Goal.Coefficients.Length;
int varCounter = numDecisionVars;
// matrix(rows, columns)
DenseMatrix coefficients = new DenseMatrix(numConstraints, numDecisionVars);
DenseMatrix artificialVars = new DenseMatrix(numConstraints, 1);
var constraintCounter = 0;
this.rhsValues = new DenseVector(numConstraints);
this.basics = new List<int>();
this.artificialRows = new List<int>();
foreach (var constraint in model.Constraints) {
rhsValues[constraintCounter] = constraint.Value;
// if the constraint RHS is negative, invert the coefficients and flip the inequality sign
if (constraint.Value < 0)
{
for (int i = 0; i< model.Goal.Coefficients.Length; i++) {
model.Goal.Coefficients[i] = model.Goal.Coefficients[i] * -1;
}
if (constraint.Relationship == Relationship.LessThanOrEquals)
{
constraint.Relationship = Relationship.GreaterThanOrEquals;
}
else if (constraint.Relationship == Relationship.GreaterThanOrEquals)
{
constraint.Relationship = Relationship.LessThanOrEquals;
}
// also flip the rhs value which we already put in the array for the simplex setup
rhsValues[constraintCounter] = rhsValues[constraintCounter] * -1;
}
coefficients.SetRow(constraintCounter, 0, constraint.Coefficients.Length, new DenseVector(constraint.Coefficients));
// if it's a less than, add a slack column to the coefs matrix
if (constraint.Relationship == Relationship.LessThanOrEquals)
{
DenseVector slack = DenseVector.Create(model.Constraints.Count, delegate(int s) { return 0; });
slack.At(constraintCounter, 1);
coefficients = (DenseMatrix)coefficients.Append(slack.ToColumnMatrix());
this.basics.Add(varCounter);
}
else
{
// Need to add an artificial variable for >= and = constraints
DenseVector surplus = DenseVector.Create(model.Constraints.Count, delegate(int s) { return 0; });
surplus.At(constraintCounter, -1);
coefficients = (DenseMatrix)coefficients.Append(surplus.ToColumnMatrix());
DenseVector artificial = DenseVector.Create(model.Constraints.Count, delegate(int s) { return 0; });
artificial.At(constraintCounter, 1);
artificialVars = (DenseMatrix)artificialVars.Append(artificial.ToColumnMatrix());
// Keeps track of the rows with artificial variable, for setting w
artificialRows.Add(constraintCounter);
}
varCounter++;
constraintCounter++;
}
// put the constraints and stuff into the matrix
if (artificialVars.ColumnCount > 1)
{
artificialVars = (DenseMatrix)artificialVars.SubMatrix(0, artificialVars.RowCount, 1, artificialVars.ColumnCount - 1);
for (int i = coefficients.ColumnCount; i < coefficients.ColumnCount + artificialVars.ColumnCount; i++)
{
this.basics.Add(i);
}
coefficients = (DenseMatrix)coefficients.Append(artificialVars);
numArtificial = artificialVars.ColumnCount;
}
else
{
numArtificial = 0;
}
return coefficients;
}
示例7: Run
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(5);
var k = 0;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = k++;
}
}
Console.WriteLine(@"Initial matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector
var vector = new DenseVector(new[] { 50.0, 51.0, 52.0, 53.0, 54.0 });
Console.WriteLine(@"Sample vector");
Console.WriteLine(vector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Insert new column
var result = matrix.InsertColumn(3, vector);
Console.WriteLine(@"1. Insert new column");
Console.WriteLine(result.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Insert new row
result = matrix.InsertRow(3, vector);
Console.WriteLine(@"2. Insert new row");
Console.WriteLine(result.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Set column values
matrix.SetColumn(2, (Vector)vector);
Console.WriteLine(@"3. Set column values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Set row values.
matrix.SetRow(3, (double[])vector);
Console.WriteLine(@"4. Set row values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Set diagonal values. SetRow/SetColumn/SetDiagonal accepts Vector and double[] as input parameter
matrix.SetDiagonal(new[] { 5.0, 4.0, 3.0, 2.0, 1.0 });
Console.WriteLine(@"5. Set diagonal values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Set submatrix values
matrix.SetSubMatrix(1, 3, 1, 3, DenseMatrix.Identity(3));
Console.WriteLine(@"6. Set submatrix values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Permutations.
// Initialize a new instance of the Permutation class. An array represents where each integer is permuted too:
// indices[i] represents that integer "i" is permuted to location indices[i]
var permutations = new Permutation(new[] { 0, 1, 3, 2, 4 });
// 7. Permute rows 3 and 4
matrix.PermuteRows(permutations);
Console.WriteLine(@"7. Permute rows 3 and 4");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Permute columns 1 and 2, 3 and 5
permutations = new Permutation(new[] { 1, 0, 4, 3, 2 });
matrix.PermuteColumns(permutations);
Console.WriteLine(@"8. Permute columns 1 and 2, 3 and 5");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 9. Concatenate the matrix with the given matrix
var append = matrix.Append(matrix);
// Concatenate into result matrix
matrix.Append(matrix, append);
Console.WriteLine(@"9. Append matrix to matrix");
Console.WriteLine(append.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 10. Stack the matrix on top of the given matrix matrix
var stack = matrix.Stack(matrix);
// Stack into result matrix
matrix.Stack(matrix, stack);
Console.WriteLine(@"10. Stack the matrix on top of the given matrix matrix");
Console.WriteLine(stack.ToString("#0.00\t", formatProvider));
//.........这里部分代码省略.........
示例8: AddRow
/// <summary>
/// adds new row to matrix
/// </summary>
/// <param name="dest">matrix which add row</param>
/// <param name="rowToAdd">row added to matrix</param>
/// <returns>new matrix</returns>
private static Matrix AddRow(Matrix dest, Vector rowToAdd)
{
Matrix res = new DenseMatrix(dest.RowCount + 1, dest.ColumnCount);
res.SetSubMatrix(0, dest.RowCount, 0, dest.ColumnCount, dest);
res.SetRow(res.RowCount - 1, rowToAdd);
return res;
}
示例9: Aca
/// <summary>
/// Adaptive Cross Approximation (ACA) matrix compression
/// the result is stored in U and V matrices like U*V
/// </summary>
/// <param name="acaThres">Relative error threshold to stop adding rows and columns in ACA iteration</param>
/// <param name="m">Row indices of Z submatrix to compress</param>
/// <param name="n">Column indices of Z submatrix to compress</param>
/// <param name="U">to store result</param>
/// <param name="V">to store result</param>
/// <returns>pair with matrix U and V</returns>
public static Tuple<Matrix, Matrix> Aca(double acaThres, List<int> m, List<int> n, Matrix U, Matrix V)
{
int M = m.Count;
int N = n.Count;
int Min = Math.Min(M, N);
U = new DenseMatrix(Min, Min);
V = new DenseMatrix(Min, Min);
//if Z is a vector, there is nothing to compress
if (M == 1 || N == 1)
{
U = UserImpedance(m, n);
V = new DenseMatrix(1, 1);
V[0, 0] = 1.0;
return new Tuple<Matrix,Matrix>(U,V);
}
//Indices of columns picked up from Z
//Vector J = new DenseVector(N);
//List<int> J = new List<int>(N);
List<int> J = new List<int>(new int [N]);
//int[] J = new int[N];
//Indices of rows picked up from Z
//Vector I = new DenseVector(M);
List<int> I = new List<int>(new int [M]);
//int[] I = new int[M];
//Row indices to search for maximum in R
//Vector i = new DenseVector(M);
List<int> i = new List<int>();
//int[] i = new int[M];
//Column indices to search for maximum in R
//Vector j = new DenseVector(N);
List<int> j = new List<int>();
//int[] j = new int[N];
for (int k = 1; k < M; k++)
{
i.Add(k);
}
for (int k = 0; k < N; k++)
{
j.Add(k);
}
//Initialization
//Initialize the 1st row index I(1) = 1
I[0] = 0;
//Initialize the 1st row of the approximate error matrix
List<int> m0 = new List<int>();
m0.Add(m[I[0]]);
Matrix Rik = UserImpedance(m0, n);
//Find the 1st column index J(0)
double max = -1.0;
int col = 0;
foreach (int ind in j)
{
if (Math.Abs(Rik[0, ind]) > max)
{
max = Math.Abs(Rik[0, ind]);
col = ind;
}
}
//J[0] = j[col];
J[0] = col;
j.Remove(J[0]);
//First row of V
V = new DenseMatrix(1, Rik.ColumnCount);
V.SetRow(0, Rik.Row(0).Divide(Rik[0, J[0]]));
//Initialize the 1st column of the approximate error matrix
List<int> n0 = new List<int>();
n0.Add(n[J[0]]);
Matrix Rjk = UserImpedance(m, n0);
//First column of U
U = new DenseMatrix(Rjk.RowCount, 1);
U.SetColumn(0, Rjk.Column(0));
// Norm of (approximate) Z, to test error
double d1 = U.L2Norm();
double d2 = V.L2Norm();
double normZ = d1 * d1 * d2 * d2;
//.........这里部分代码省略.........
示例10: Predict
public void Predict(DenseMatrix newPredictData, double[] newPredictPrices)
{
double error = 0;
int c = 0;
var newNormalizedPredictData = new DenseMatrix(newPredictData.RowCount, newPredictData.ColumnCount,
double.NaN);
for (int i = 0; i < newPredictData.RowCount; i++)
{
newNormalizedPredictData.SetRow(i, normalizeArrayInput[i].Process(newPredictData.Row(i).ToArray()));
}
double[] normalizedPrices = normalizeArrayOutput.Process(newPredictPrices);
var d = new DenseMatrix(2, normalizedPrices.Length + 1, double.NaN);
int count = 0;
for (int i = 0; i < normalizedPrices.Length; i++)
{
// calculate based on actual data
IMLData input = new BasicMLData(inputs);
for (int j = 0; j < input.Count; j++)
{
input.Data[j] = newNormalizedPredictData[j, i];
}
IMLData output = network.Compute(input);
double prediction = output.Data[0];
error +=
Math.Pow(
(normalizeArrayOutput.Stats.DeNormalize(prediction) - newPredictPrices[i])/newPredictPrices[i],
2);
c++;
d[0, count] = newPredictPrices[i];
d[1, count] = normalizeArrayOutput.Stats.DeNormalize(prediction);
count++;
}
/////////////////////////////////////////////////////////////////
IMLData input1 = new BasicMLData(inputs);
for (int j = 0; j < input1.Count; j++)
{
input1.Data[j] = newNormalizedPredictData[j, newNormalizedPredictData.ColumnCount - 1];
}
IMLData output1 = network.Compute(input1);
d[1, count] = normalizeArrayOutput.Stats.DeNormalize(output1.Data[0]);
/////////////////////////////////////////////////////////////////
error /= c;
error = Math.Pow(error, .5);
Console.WriteLine(error);
string[] symbols = {"actual", "predicted"};
Visualize.GeneratePredictionGraph(symbols, d, new DateTime(), new TimeSpan(24, 0, 0),
"C:\\Sangar\\resultfinal.html");
outputCorre =
StatisticsExtension.Correlation(d.Row(0).ToArray().Take(d.ColumnCount - 1).ToArray().RawRateOfReturn(),
d.Row(1).ToArray().Take(d.ColumnCount - 1).ToArray().RawRateOfReturn());
Console.WriteLine("ST2 Correlation: " + outputCorre);
outputRMSE = error;
Console.WriteLine("Predicted return for D+1:" +
(d[1, d.ColumnCount - 1] - d[1, d.ColumnCount - 2])/d[1, d.ColumnCount - 2]*100 +
" percent");
}
示例11: Execute
public void Execute()
{
var nnSet = new Stage1NeuralNetwork[vectors.Length];
int trainLength = 2000;
int validationLength = 500;
int predictLength = 500;
int useLength = 3000;
var totalData = new DenseMatrix(vectors.Length, useLength);
var outputData = new DenseMatrix(vectors.Length, validationLength - window);
/////////////////populate the actual price data we want to predict
var pricingData = new double[useLength];
for (int i = 2; i < 2 + useLength; i++)
{
pricingData[i - 2] = (double) data[useLength + 3 - i, 5];
}
double[] returnpricingData = pricingData.RawRateOfReturn();
for (int i = 0; i < returnpricingData.Length; i++) pricingData[i + 1] = returnpricingData[i];
pricingData[0] = 0;
////////////////////////training and validation////////////////////////
for (int i = 2; i < 2 + useLength; i++)
{
for (int j = 0; j < vectors.Length; j++)
{
totalData[j, i - 2] = (double) data[useLength + 3 - i, vectors[j]];
}
}
for (int j = 0; j < vectors.Length; j++)
{
double[] train = totalData.Row(j).ToArray().Take(trainLength).ToArray();
double[] validate =
totalData.Row(j).ToArray().Skip(trainLength).ToArray().Take(validationLength).ToArray();
nnSet[j] = new Stage1NeuralNetwork(window, cycles, train, validate);
nnSet[j].Execute(j);
outputData.SetRow(j, nnSet[j].OutputData);
}
var s1 = new Stage2NeuralNetwork(vectors.Length, cycles, outputData,
pricingData.Skip(trainLength).ToArray().Take(validationLength).ToArray().Skip(window).ToArray());
s1.Execute();
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////prediction/////////////////////////////
var predictedData = new DenseMatrix(vectors.Length, predictLength - window + 1);
var lastPredData = new double[vectors.Length];
for (int j = 0; j < vectors.Length; j++)
{
double[] predictData =
totalData.Row(j)
.ToArray()
.Skip(trainLength + validationLength)
.ToArray()
.Take(predictLength)
.ToArray();
nnSet[j].Predict(predictData);
predictedData.SetRow(j, nnSet[j].OutputData);
lastPredData[j] = nnSet[j].NextPrediction;
}
s1.Predict(predictedData,
pricingData.ToArray()
.Skip(trainLength + validationLength)
.ToArray()
.Take(predictLength)
.ToArray()
.Skip(window)
.ToArray());
correlation = s1.outputCorre;
RMSE = s1.outputRMSE;
}
示例12: solveActuator2CartesianDisp
private void solveActuator2CartesianDisp(double[] adisp)
{
bool check = false;
DenseVector cartDisp = new DenseVector(6);
DenseVector newAct = new DenseVector(adisp);
DenseVector actError = (DenseVector)newAct.Subtract(actuatorDisp);
cartesianDisp.CopyTo(cartDisp);
int iterations = 0;
while (check == false)
{
List2String l2s = new List2String();
DenseMatrix JacobianMatrix = new DenseMatrix(6, 6);
for (int i = 0; i < 6; i++)
{
DenseVector DL_Dd = actuators[i].calcNewDiffs(cartDisp.Values);
JacobianMatrix.SetRow(i, DL_Dd);
}
DenseVector diffCart = (DenseVector)JacobianMatrix.LU().Solve(actError);
log.Debug("Cartesian differences " + l2s.ToString(diffCart.Values));
cartDisp = (DenseVector)cartDisp.Add(diffCart);
setCartesianDisp(cartDisp.Values);
log.Debug("New cartesian estimate " + this);
actError = (DenseVector)newAct.Subtract(actuatorDisp);
log.Debug("Actuator error " + l2s.ToString(actError.Values));
check = withinErrorWindow(actError);
if (iterations > 20)
{
check = true;
log.Error("Calculations for " + label + " won't converge with " + this);
}
iterations++;
}
}
示例13: RidgeRegression
/// <summary>
/// Solve the ridge equation by the method of normal equations.
/// </summary>
/// <param name="x">[n_samples, n_features]
/// Training data</param>
/// <param name="y">[n_samples, n_targets]
/// Target values</param>
/// <param name="alpha"></param>
/// <param name="sampleWeight">Individual weights for each sample.</param>
/// <param name="solver">Solver to use in the computational routines.</param>
/// <param name="maxIter">Maximum number of iterations for least squares solver. </param>
/// <param name="tol">Precision of the solution.</param>
/// <returns>[n_targets, n_features]
/// Weight vector(s)</returns>
/// <remarks>
/// This function won't compute the intercept;
/// </remarks>
public static Matrix<double> RidgeRegression(
Matrix<double> x,
Matrix<double> y,
double alpha,
Vector<double> sampleWeight = null,
RidgeSolver solver = RidgeSolver.Auto,
int? maxIter = null,
double tol = 1E-3)
{
int nSamples = x.RowCount;
int nFeatures = x.ColumnCount;
if (solver == RidgeSolver.Auto)
{
// cholesky if it's a dense array and lsqr in
// any other case
if (x is DenseMatrix)
{
solver = RidgeSolver.DenseCholesky;
}
else
{
solver = RidgeSolver.Lsqr;
}
}
if (sampleWeight != null)
{
solver = RidgeSolver.DenseCholesky;
}
if (solver == RidgeSolver.Lsqr)
{
// According to the lsqr documentation, alpha = damp^2.
double sqrtAlpha = Math.Sqrt(alpha);
Matrix coefs = new DenseMatrix(y.ColumnCount, x.ColumnCount);
foreach (var column in y.ColumnEnumerator())
{
Vector<double> c = Lsqr.lsqr(
x,
column.Item2,
damp: sqrtAlpha,
atol: tol,
btol: tol,
iterLim: maxIter).X;
coefs.SetRow(column.Item1, c);
}
return coefs;
}
if (solver == RidgeSolver.DenseCholesky)
{
//# normal equations (cholesky) method
if (nFeatures > nSamples || sampleWeight != null)
{
// kernel ridge
// w = X.T * inv(X X^t + alpha*Id) y
var k = x.TransposeAndMultiply(x);
Vector<double> sw = null;
if (sampleWeight != null)
{
sw = sampleWeight.Sqrt();
// We are doing a little danse with the sample weights to
// avoid copying the original X, which could be big
y = y.MulColumnVector(sw);
k = k.PointwiseMultiply(sw.Outer(sw));
}
k.Add(DenseMatrix.Identity(k.RowCount)*alpha, k);
try
{
var dualCoef = k.Cholesky().Solve(y);
if (sampleWeight != null)
dualCoef = dualCoef.MulColumnVector(sw);
return x.TransposeThisAndMultiply(dualCoef).Transpose();
}
catch (Exception) //todo:
{
//.........这里部分代码省略.........
示例14: FindLinearEstimationOfCameraMatrix
public Matrix<double> FindLinearEstimationOfCameraMatrix()
{
Matrix<double> equationsMat = new DenseMatrix(2 * Points.Count, 12);
for(int p = 0; p < Points.Count; p++)
{
// Fill matrix A with point info
equationsMat.SetRow(2 * p, new double[12] {
0, 0, 0, 0,
-RealPoints[0, p], -RealPoints[1, p], -RealPoints[2, p], -1.0f,
ImagePoints[1, p] * RealPoints[0, p], ImagePoints[1, p] * RealPoints[1, p],
ImagePoints[1, p] * RealPoints[2, p], ImagePoints[1, p] });
equationsMat.SetRow(2 * p + 1, new double[12] {
RealPoints[0, p], RealPoints[1, p], RealPoints[2, p], 1.0f,
0, 0, 0, 0,
-ImagePoints[0, p] * RealPoints[0, p], -ImagePoints[0, p] * RealPoints[1, p],
-ImagePoints[0, p] * RealPoints[2, p], -ImagePoints[0, p]});
}
_linearSolver.EquationsMatrix = equationsMat;
_linearSolver.Solve();
Vector<double> p_vec = _linearSolver.ResultVector;
Matrix<double> cameraMatrix = new DenseMatrix(3, 4);
cameraMatrix.SetRow(0, p_vec.SubVector(0, 4));
cameraMatrix.SetRow(1, p_vec.SubVector(4, 4));
cameraMatrix.SetRow(2, p_vec.SubVector(8, 4));
return cameraMatrix;
}
示例15: FinishAndProcess
public void FinishAndProcess()
{
try
{
var priceData = new DenseMatrix(symbols.Length, numTicks);
for (int j = 0; j < symbols.Length; j++)
{
SortedList<DateTime, Tick> d = mktData[j].data.Data;
for (int k = 0; k < d.Count; k++)
{
//if (!symbols[j].Substring(0, 3).Equals("USD")) priceData[j, k] = 1/d.Values[k].BidClose;
priceData[j, k] = d.Values[k].BidOpen;
}
}
Vector<double> price1 = priceData.Row(0);
Vector<double> price2 = priceData.Row(1);
//Statistics.ApplyFunction((DenseVector)price1, Math.Log);
//Statistics.ApplyFunction((DenseVector)price2, Math.Log);
DenseVector norm1 = price1.ToArray().NormalizeZScore();
DenseVector norm2 = price2.ToArray().NormalizeZScore();
var newsym = new string[symbols.Length + 4];
for (int i = 0; i < symbols.Length; i++) newsym[i] = symbols[i];
newsym[2] = "spread";
newsym[3] = "EMA5";
newsym[4] = "EMA15";
newsym[5] = "EMA30";
var m = new DenseMatrix(6, norm1.Count);
m.SetRow(0, norm1);
m.SetRow(1, norm2);
m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());
m.SetRow(3, EMA.CalcEMA(m.Row(2).ToArray(), 5));
m.SetRow(4, EMA.CalcEMA(m.Row(2).ToArray(), 15));
m.SetRow(5, EMA.CalcEMA(m.Row(2).ToArray(), 30));
string filename = symbols[0].Replace('/', '_') + "-" + symbols[1].Replace('/', '_') + ".html";
((DenseVector) m.Row(0)).GenerateSimpleGraph("C:\\Sangar\\result.html");
Visualize.GenerateMultiSymbolGraph(newsym, m, DateTime.Now.AddSeconds(-60*5*300), new TimeSpan(0, 5, 0),
"C:\\Sangar\\" + filename);
FileUpload.UploadFileToFTP("C:\\Sangar\\" + filename, filename);
Spread = m[2, m.ColumnCount - 1];
if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Above 2.0", "Test");
if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Below -2.0", "Test");
//if (m[2, m.ColumnCount - 1] < 0.5 && m[2, m.ColumnCount - 2] >= 0.5)
// Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Below 0.5", "Test");
//if (m[2, m.ColumnCount - 1] > -0.5 && m[2, m.ColumnCount - 2] <= -0.5)
// Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Above -0.5", "Test");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}