I have a function that works for vector inputs but I need to run this on a cube. My impulse is I need to slice a vector out of the cube and then run it over a double for loop.
This is the pseudo code:
public static double[,,] cubefunction(double[,,] input)
{
int N = input.GetLength(0);
var outputvector = new double[N,N,N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
outputvector[1:N,i,j] = vectorfunction(input[1:N,i,j]);
}
}
return outputvector;
}
Obviously, 1:N is matlab notation to grab the entire row. Is there an equivalent in C#? Or how would I go about this without triple looping?
Related
The network produces 1 x N x K tensor, where N is number of pixel positions and K is number of classes, each value represents score for a class at given position.
Current code to retrieve best class affinity for each position is working, but it is terribly slow and takes x4 more time, than the network run itself.
private int[,] GetClasses(List<DisposableNamedOnnxValue> output)
{
Tensor<float> outTensor = output.First().AsTensor<float>();
int[,] classes = new int[frameWidth,frameHeight];
for (int i = 0; i < frameWidth; ++i)
{
for (int j = 0; j < frameHeight; ++j)
{
int finalClass = 0;
float finalClassScore = 0;
for (int k = 0; k < nClasses; ++k)
{
float score = outTensor[0, i * frameHeight + j, k];
if (score > finalClassScore)
{
finalClassScore = score;
finalClass = k;
}
}
classes[i, j] = finalClass;
}
}
return classes;
}
Is there a better, faster way of doing this in Microsoft.ML ?
The solution I went with was to add argmax layer to the initial keras model. Keras output single value through argmax.
My problem is I have M subproblem. Each subproblem include x (double array) and reduced cost which has different value for each iteration m. I want to show x which has the minimum reduced cost among all subproblems. here is my class:
public class Subproblem
{
public double[,] x { get; set; }
public double ReducedCost { get; set; }
}
So far, I already can get the minimum Reduced Cost and index of it. Now I want to show x value (double array) which on that index. I've code like this:
var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];
s.ReducedCost = model.ObjVal;
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
s.x[i, j] = x[i, j].X;
}
}
sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));
the last line (Console.WriteLine(sub.x(minRCIndex));) still got red underline, I don't know how to write it
If you are only trying to get the minimum Reduced Costed subproblem you should be doing:
Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];
And you can print the matrix down like this:
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
}
Console.Write("\n");
}
But you seem a little confused. You are pushing a Subproblem into your sub list with the same object for M times. Because model.ObjVal doesn't change along the first for loop. There is something wierd going on there too.
It should be
var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.WriteLine(objWithMinReduceCost.x[i, j]);
}
}
If you are interested in obtaining the double array, you could just do this:
double[,] result = sub.First(i => i.ReducedCost == minRC).x;
Although as Tolga mentioned, all your elements will have the same ReducedCost with your current code.
In the example below, I found a strange behaviour.
I'm initializing a matrix of Complex (using System.Numerics), assigning a counter value for each position.
But at a certain moment the procedure override the previous cells.
What's wrong there is there any array limit?
it seems the Complex type the issue, with a double array this doesn't happen.
Any suggestion?
private static void Test()
{
Complex[,] m = new Complex[16400, 16400];
long count = 1;
for (int i = 0; i < 16400; i++)
{
for (int j = 0; j < 16400; j++)
{
m[i, j] = new Complex((double)count++, 0);
if (m[0,0] != 1)
Debug.Print(string.Format("({0},{1})> m[0,0] =" + m[0, 0].ToString(), i,j));
}
}
}
i've made a function for FFT using AForge. It seems to work but when i'm checking with my supervisor he says the output is not correct. He is using the PWelch function from MatLab. We've already found out we were using different windows but changing them didn't make a significant difference. So again, the function does work but according to my supervisor the output is incorrect. Please Help!
This is my Function, i hope anyone sees something that's wrong because i've been looking at it for allmost two weeks now. The DATA that goes into it is already made equidistant.
private void FastFoulierMethod()
{
int NFFT = 64;
int N_OVERLAP = 32;
int numberOfEpochs = samples.Count / NFFT;
int numberOfSamplesToSelectFromFFT = NFFT-1;
double[] dataaa = new double[samples.Count];
for (int i = 0; i < samples.Count - 1; i++)
{
dataaa[i] = samples[i].GetValue();//lijst met doubles die we gebruiken
}
double[,] pFrame = new double[numberOfEpochs, numberOfSamplesToSelectFromFFT];
// The first epoch in the page starts at index 0
int beginIndexOfEpoch = 0;
for (int i = 0; i < numberOfEpochs; i++)
{
// This will get the current epoch by retrieving samples from the sample list
// starting at 'beginIndex' with length 'NFFT'. This epoch will need to be detrended next.
List<double> smapletemp = new List<double>();
for (int x = beginIndexOfEpoch; x < beginIndexOfEpoch+NFFT; x++)
{
smapletemp.Add(dataaa[x]);
}
double[] epoch = smapletemp.ToArray();
if (epoch.Length == 0)
{
break;
}
// Create array of X-axis values 1,2,3,4 ... n
// which will be used to perform linear regression.
double[] xValues = new double[epoch.Length];
for (int j = 0; j < xValues.Length; j++)
{
xValues[j] = j;
}
// Perform linear regression on the epoch. This will result in some data that is used later.
Dictionary<String, double> linearRegressionData = math.performLinearRegression(xValues.ToList(), epoch.ToList());
// Detrend the epoch
for (int j = 0; j < epoch.Length; j++)
{
double intercept = linearRegressionData["Alpha"]; // Get the intercept from the data.
double slope = linearRegressionData["Beta"]; // Get the slope from the data.
//if (1 >= math.StdDev(epoch))
//{
epoch[j] = epoch[j] - intercept - (slope * j); // Detrend the epoch by subtracting the intercept and the slope * j.
//}
}
// Create Complex from the epoch for windowing and FFT processing.
Complex[] cmplx = new Complex[epoch.Length];
for (int j = 0; j < cmplx.Length; j++)
{
cmplx[j] = new Complex(epoch[j], 0);
}
// Perform Hann window function on the Complex.
math.hann(cmplx);
// Perform Fast Fourier Transform on the Complex.
FourierTransform.FFT(cmplx, FourierTransform.Direction.Backward);
// Create an array for all powers.
double[] powers = new double[cmplx.Length];
for (int j = 0; j < epoch.Length; j++)
{
powers[j] = cmplx[j].SquaredMagnitude;
}
// Add the powers to the power frame.
for (int j = 0; j < powers.Length-1; j++)
{
pFrame[i, j] = powers[j];
}
// Shift index for the next epoch.
beginIndexOfEpoch += NFFT - N_OVERLAP;
if ( beginIndexOfEpoch + NFFT > samples.Count)
{
break;
}
}
// Create an array for the nan-mean values of all epochs.
// Nan-mean calculates the mean of a set of doubles, ignoring NaN's.
double[] nanMeanValues = new double[numberOfSamplesToSelectFromFFT];
List<double[]> Y = new List<double[]>();
for (int i = 0; i < numberOfSamplesToSelectFromFFT; i++)
{
// The sum for calculating the mean.
double sum = 0.0;
// The number of elements (doubles) for calculating the mean.
int count = 0;
// For all epochs...
for (int j = 0; j < numberOfEpochs; j++)
{
// ...the mean for all doubles at index 'i' is calculated.
double sample = pFrame[j, i];
if (!Double.IsNaN(sample))
{
// Only take the double into account when it isn't a NaN.
sum += sample;
count++;
}
}
// Actually calculate the mean and add it to the array.
nanMeanValues[i] = sum / count;
}
// We now have the mean of all power arrays (or epochs).
// Create an array with Root Mean Square values.
double[] squareRootedNanMeans = new double[nanMeanValues.Length];
for (int i = 0; i < squareRootedNanMeans.Length; i++)
{
squareRootedNanMeans[i] = Math.Sqrt(nanMeanValues[i]);
}
Y.Add(squareRootedNanMeans);
It's been ages since I studied FFT's but, unless you academic assignment is to produce an fft function, I advise you to use some library. It is great to program your own stuff to learn, but if you need results, go for the sure thing.
You can use Alglib {http://www.alglib.net/fasttransforms/fft.php}, which has a free version.
Hope this helps.
I am trying to generate random numbers 0-49. I want to draw the links in a grid as long as the random number is not 0. Every time I do get a 0, it is followed by another ten 0s (give or take). In my research, they said this would be the problem if I kept creating new instances of my Random, but I am not doing that. My code is as follows:
//Class begins
namespace Mascape
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Wall[, ,] walls = new Wall[2, 15, 10];
int mapWidth=15;
int mapHeight=10;
Random rand = new Random(); //Outside of any methods or loops.
int mapFullness;
//The following is in my Initialize() method
//i is horizontal vs. vertical link
//j is the x position of the link
//k is the y position of the link
mapFullness = 50;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < mapWidth; ++j)
{
for (int k = 0; k < mapHeight; ++k)
{
if (!(rand.Next(50) == 0))
{
walls[i, j, k].active = true; //Links are drawn if active
}
}
}
}
I am trying to draw a grid with randomly missing links. The objective is to have them spread out, appearing about one in 50. This is the actual result:
Any idea why the randomness is lacking? Let me know if you would like more info, please.
There should be more to this. See the following code copied from yours generate random as expected.
Random rand = new Random();
int mapWidth = 5;
int mapHeight = 10;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < mapWidth; ++j)
{
for (int k = 0; k < mapHeight; ++k)
{
Console.WriteLine(rand.Next(50));
}
}
}