本文整理汇总了C#中MathNet.Numerics.Distributions.Normal.Sample方法的典型用法代码示例。如果您正苦于以下问题:C# Normal.Sample方法的具体用法?C# Normal.Sample怎么用?C# Normal.Sample使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MathNet.Numerics.Distributions.Normal
的用法示例。
在下文中一共展示了Normal.Sample方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ColumnInitNormal
/// <summary>Initializes one column of a float matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
/// <param name="column">the column to be initialized</param>
static public void ColumnInitNormal(this Matrix<float> matrix, int column, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = MyMediaLite.Random.GetInstance();
for (int i = 0; i < matrix.dim1; i++)
matrix[i, column] = (float) nd.Sample();
}
示例2: InitNormal
/// <summary>Initializes a float matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
static public void InitNormal(this Matrix<float> matrix, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = MyMediaLite.Random.GetInstance();
for (int i = 0; i < matrix.data.Length; i++)
matrix.data[i] = (float) nd.Sample();
}
示例3: RowInitNormal
/// <summary>Initializes one row of a float matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="row">the row to be initialized</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
static public void RowInitNormal(this Matrix<float> matrix, int row, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = MyMediaLite.Random.GetInstance();
for (int j = 0; j < matrix.dim2; j++)
matrix[row, j] = (float) nd.Sample();
}
示例4: ColumnInitNormal
/// <summary>Initializes one column of a double matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
/// <param name="column">the column to be initialized</param>
public static void ColumnInitNormal(this Matrix<double> matrix, int column, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = Util.Random.GetInstance();
for (int i = 0; i < matrix.dim1; i++)
matrix[i, column] = nd.Sample();
}
示例5: InitNormal
/// <summary>Initialize a collection of floats with values from a normal distribution</summary>
/// <param name="vector">the vector to initialize</param>
/// <param name="mean">the mean of the normal distribution</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
static public void InitNormal(this IList<float> vector, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = MyMediaLite.Random.GetInstance();
for (int i = 0; i < vector.Count; i++)
vector[i] = (float) nd.Sample();
}
示例6: Initialize
public override void Initialize(List<Agent> agents)
{
var appSettings = ConfigurationManager.AppSettings;
var activityMean = int.Parse(appSettings["RegularAgentActivityMean"]);
var activityStd = int.Parse(appSettings["RegularAgentActivityStd"]);
var distribution = new Normal(activityMean, activityStd);
var interval = distribution.Sample();
ActivityInterval = (int)interval;
var contactsMean = int.Parse(appSettings["RegularAgentContactsMean"]);
var contactsStd = int.Parse(appSettings["RegularAgentContactsStd"]);
distribution = new Normal(contactsMean, contactsStd);
var contactsNumber = 0;
while (contactsNumber == 0)
{
contactsNumber = (int)distribution.Sample();
}
var strongConnectionsMean = int.Parse(appSettings["RegularAgentStrongConnectionsMean"]);
var strongConnectionsStd = int.Parse(appSettings["RegularAgentStrongConnectionsStd"]);
distribution = new Normal(strongConnectionsMean, strongConnectionsStd);
var strongConnectionsNumber = (int)distribution.Sample();
var strongConnectionsInterval = 0.75 / strongConnectionsNumber;
var strongConnectionsIntervalMin = 0.8 * strongConnectionsInterval;
var strongConnectionsIntervalDiff = strongConnectionsInterval - strongConnectionsIntervalMin;
var random = new Random();
var total = 1.0;
var usedIndices = new List<int>();
for (int i = 0; i < contactsNumber; i++)
{
var currentAgentIndex = random.Next(agents.Count);
if (usedIndices.Contains(currentAgentIndex))
{
i--;
continue;
}
usedIndices.Add(currentAgentIndex);
var currentAgent = agents.ElementAt(currentAgentIndex);
var probability = 0.0;
if (i < strongConnectionsNumber)
{
probability = strongConnectionsIntervalMin + random.NextDouble() * strongConnectionsIntervalDiff;
}
else
{
if(i == contactsNumber - 1)
{
probability = total;
}
else
{
probability = 0.2 * total;
}
}
total -= probability;
Contacts.Add(currentAgent, probability);
}
}
示例7: Paths
public static IEnumerable<double> Paths(double S, double sigma, double maturity, double N)
{
double var = sigma*sigma*maturity;
Normal n = new Normal();
for (int i = 0; i < N; i++ )
{
double normalsample = n.Sample();
double Sf = S * Math.Exp(-0.5 * var + Math.Sqrt(var) * normalsample);
yield return Sf;
}
}
示例8: NormalDistSample
public object NormalDistSample(int mean, int stddev, int size, int nbuckets)
{
var normal = new Normal(mean, stddev);
var data = new double[size];
for (var i = 0; i < data.Length; i++)
{
data[i] = normal.Sample();
}
var histogram = new Histogram(data, nbuckets);
var buckets = new List<Bucket>();
for (var i = 0; i < histogram.BucketCount; i++)
{
buckets.Add(histogram[i]);
}
return buckets.Select(x=> new {lowerBound = x.LowerBound, upperBound = x.UpperBound, count = x.Count}).ToList();
}
示例9: CanSample
public void CanSample()
{
var n = new Normal();
n.Sample();
}
示例10: Main
static void Main(string[] args)
{
GlobValues glob = new GlobValues();
string configFile, dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), inputPath, outputPath;
String[] path = dir.Split(new string[] { "Launch" }, StringSplitOptions.None);
inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "input";
configFile = inputPath + Path.DirectorySeparatorChar + "config.param.txt";
// outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "output";
Console.WriteLine("File is : " + configFile);
Console.WriteLine("Starting the program to generate the network based on modularity..");
try
{
// Read parameters from param.config file
read_parameters(configFile, glob);
}
catch
{
Console.WriteLine("Usage: mono Demo.exe [nodes] [edges] [clusters] [resultfile]");
return;
}
// Displays the information
Console.WriteLine("Given Parameter values");
Console.WriteLine("\n Nodes: " + glob.nodes + "\n Edges: " + glob.edges + "\n Clusters: " + glob.clusters + "\n Modularity MinValue: " + glob.modularityMinValue + "\n Modularity MaxValue: " + glob.modularityMaxValue);
Console.WriteLine(" Number of runs: " + glob.numberOfGraphs + "\n Coupling probability value: "+glob.couplingProb*100);
string sourceNetworkFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "network.edges";
string sourceResultFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "result.dat";
// For loop to make n number of Networks with the given size and modularity ...
double modularity = glob.modularityMinValue;
while (modularity <= glob.modularityMaxValue)
{
String outputFile = "Result_M" + modularity;
outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + outputFile;
System.IO.Directory.CreateDirectory(outputPath);
try
{
for (int n = 1; n <= glob.numberOfGraphs; n++)
{
network = new ClusterNetwork(glob.nodes, glob.edges, glob.clusters, modularity, true);
// Restricting the modularity value upto 1 decimal place
// modularity = Math.Round(network.NewmanModularityUndirected, 1);
String memberOutputFile = outputPath + Path.DirectorySeparatorChar + "membership.dat";
System.IO.StreamWriter sw = System.IO.File.CreateText(memberOutputFile);
int i = 0;
foreach (Vertex v in network.Vertices)
{
v.Label = (i++).ToString();
sw.WriteLine(network.GetClusterForNode(v).ToString());
}
sw.Close();
Network.SaveToEdgeFile(network, "network.edges");
Console.WriteLine("Created network with {0} vertices, {1} edges and modularity {2:0.00}", network.VertexCount, network.EdgeCount, modularity);
// To move a file or folder to a new location without renaming it. We rename the files after running the Kuramoto model.
string destinationResultFile = outputPath + Path.DirectorySeparatorChar + n + "_res_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat";
string destinationNetworkFile = outputPath + Path.DirectorySeparatorChar + n + "_network_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".edges";
System.IO.File.Move(outputPath + Path.DirectorySeparatorChar + "membership.dat", outputPath + Path.DirectorySeparatorChar + n + "_mem_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat");
try
{
Console.WriteLine("Moving the generated files to output directory..");
System.IO.File.Move(sourceNetworkFile, destinationNetworkFile);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
// Run the Kuramoto model here and store the results in the output directory
NetworkColorizer colorizer = new NetworkColorizer();
// Distribution of natural frequencies
double mean_frequency = 1d;
Normal normal = new Normal(mean_frequency, mean_frequency / 5d);
sync = new Kuramoto(network,
glob.couplingStrength,
glob.couplingProb,
colorizer,
new Func<Vertex, Vertex[]>(v => { return new Vertex[] { v.RandomNeighbor }; })
);
foreach (Vertex v in network.Vertices)
sync.NaturalFrequencies[v] = normal.Sample();
foreach (int g in network.ClusterIDs)
pacemaker_mode[g] = false;
sync.OnStep += new Kuramoto.StepHandler(recordOrder);
//.........这里部分代码省略.........
示例11: CreateProximalSegments
/// <summary>
/// For each (position in inputSpaceRandomPositions):
/// 1. Create a new InputCell with input bit = position
/// 2. Attach a new ProximalSynapse
/// 3. Add the synapse to the synapse update list.
/// </summary>
/// <remarks>
/// Prior to receiving any inputs, the region is initialized by computing a list of
/// initial potential synapses for each column. This consists of a random set of inputs
/// selected from the input space. Each input is represented by a synapse and assigned
/// a random permanence value. The random permanence values are chosen with two
/// criteria. First, the values are chosen to be in a small range around connectedPerm
/// (the minimum permanence value at which a synapse is considered "connected"). This
/// enables potential synapses to become connected (or disconnected) after a small
/// number of training iterations. Second, each column has a natural center over the
/// input region, and the permanence values have a bias towards this center (they
/// have higher values near the center).
///
/// The concept of Locality Radius is an additional parameter to control how
/// far away synapse connections can be made instead of allowing connections anywhere.
/// The reason for this is that in the case of video images I wanted to experiment
/// with forcing each Column to only learn on a small section of the total input to
/// more effectively learn lines or corners in a small section.
/// </remarks>
internal void CreateProximalSegments()
{
// Calculates inputRadius for Columns from localityRadius
//var inputRadius = (int)Math.Round ( this.Region.LocalityRadius * this.Region.InputProportionX );
// JS
// JS - should there be 2 inputRadiae, for X and Y, to allow for non-square input fields?
//(1)
var inputRadius = (int) Math.Max( 1, Math.Round(this.Region.LocalityRadius * this.Region.InputProportionX));
//inputRadius = (int)Math.Max ( 1, Math.Round ( this.Region.PercentageInputPerColumn * this.Region.InputSize.Height * this.Region.InputSize.Width ) / 2 );
//var inputRadius = (int)Math.Max ( 1, Math.Round ( this.Region.LocalityRadius * Math.Max ( this.Region.InputProportionX, this.Region.InputProportionY ) ) );
// The coordinates of the input space for the Column
// Think of input space like a 'imaginary' square below the column center.
int minY, maxY, minX, maxX;
//(2)
if (this.Region.LocalityRadius > 0)
{
// Compute values of input square and cut radius on edges
minX = Math.Max ( 0, this.CentralPositionInInput.X - inputRadius);
maxX = Math.Min(this.Region.InputSize.Width - 1,
this.CentralPositionInInput.X + inputRadius);
minY = Math.Max ( 0, this.CentralPositionInInput.Y - inputRadius);
maxY = Math.Min(this.Region.InputSize.Height - 1,
this.CentralPositionInInput.Y + inputRadius);
}
else
{
minX = 0;
minY = 0;
maxX = this.Region.InputSize.Width - 1;
maxY = this.Region.InputSize.Height - 1;
}
// Compute input area
// (3)
int inputArea = (maxX - minX + 1) * (maxY - minY + 1);
// Proximal synapses per Column (input segment)
// TODO: give user some control over the number of synapses per segment
//var synapsesPerSegment =
//debug js
// (int) (inputArea * this.Region.PercentageInputPerColumn);
// (4)
var synapsesPerSegment = Math.Max(1, (int)(inputArea * this.Region.PercentageInputPerColumn));
// JS
//synapsesPerSegment = Math.Max ( 1, (int)(inputArea * this.Region.InputProportionX) );
// Updates minimum overlap value, i.e. the minimum number of inputs that must
// be active for a column to be considered during the inhibition step.
//debug js
//this.MinOverlap =
// (int) Math.Round(synapsesPerSegment * this.Region.PercentageMinOverlap);
// (5)
this.MinOverlap = Math.Max(1,
(int)Math.Round ( synapsesPerSegment * this.Region.PercentageMinOverlap ));
// Create all possible x,y positions for this column input space
// (6)
var inputPositions = new List<Point>();
for (int y = minY; y <= maxY; y++)
{
for (int x = minX; x <= maxX; x++)
{
var inputPosition = new Point(x, y);
inputPositions.Add(inputPosition);
}
}
// Random sample of unique input positions (no duplicates).
// Tie the random seed to this Column's position for reproducibility
int randomSeed = (this.PositionInRegion.Y * this.Region.Size.Width) + this.PositionInRegion.X;
// (7)
IEnumerable<Point> inputRandomPositions =
inputPositions.RandomSample(synapsesPerSegment, randomSeed, false);
//.........这里部分代码省略.........
示例12: RunAggregation
private static AggregationResult RunAggregation(ClusterNetwork net, double bias)
{
Dictionary<Vertex, double> _attributes = new Dictionary<Vertex, double>();
Dictionary<Vertex, double> _aggregates = new Dictionary<Vertex, double>();
MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0d, 5d);
AggregationResult result = new AggregationResult();
result.Modularity = net.NewmanModularityUndirected;
double average = 0d;
foreach (Vertex v in net.Vertices)
{
_attributes[v] = normal.Sample();
_aggregates[v] = _attributes[v];
average += _attributes[v];
}
average /= (double)net.VertexCount;
double avgEstimate = double.MaxValue;
result.FinalVariance = double.MaxValue;
result.FinalOffset = 0d;
for (int k = 0; k < Properties.Settings.Default.ConsensusRounds; k++)
{
foreach (Vertex v in net.Vertices.ToArray())
{
Vertex w = v.RandomNeighbor;
List<Vertex> intraNeighbors = new List<Vertex>();
List<Vertex> interNeighbors = new List<Vertex>();
ClassifyNeighbors(net, v, intraNeighbors, interNeighbors);
double r = net.NextRandomDouble();
if (r <= bias && interNeighbors.Count > 0)
w = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));
_aggregates[v] = aggregate(_aggregates[v], _aggregates[w]);
_aggregates[w] = aggregate(_aggregates[v], _aggregates[w]);
}
avgEstimate = 0d;
foreach (Vertex v in net.Vertices.ToArray())
avgEstimate += _aggregates[v];
avgEstimate /= (double)net.VertexCount;
result.FinalVariance = 0d;
foreach (Vertex v in net.Vertices.ToArray())
result.FinalVariance += Math.Pow(_aggregates[v] - avgEstimate, 2d);
result.FinalVariance /= (double)net.VertexCount;
double intraVar = 0d;
foreach (int c in net.ClusterIDs)
{
double localavg = 0d;
double localvar = 0d;
foreach (Vertex v in net.GetNodesInCluster(c))
localavg += _aggregates[v];
localavg /= net.GetClusterSize(c);
foreach (Vertex v in net.GetNodesInCluster(c))
localvar += Math.Pow(_aggregates[v] - localavg, 2d);
localvar /= net.GetClusterSize(c);
intraVar += localvar;
}
intraVar /= 50d;
//Console.WriteLine("i = {0:0000}, Avg = {1:0.000}, Estimate = {2:0.000}, Intra-Var = {3:0.000}, Total Var = {4:0.000}", result.iterations, average, avgEstimate, intraVar, totalVar);
}
result.FinalOffset = average - avgEstimate;
return result;
}
示例13: RowInitNormal
/// <summary>Initializes one row of a double matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="row">the row to be initialized</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
public static void RowInitNormal(this Matrix<double> matrix, int row, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = Util.Random.GetInstance();
for (int j = 0; j < matrix.dim2; j++)
matrix[row, j] = nd.Sample();
}
示例14: InitNormal
/// <summary>Initializes a float matrix with normal distributed (Gaussian) noise</summary>
/// <param name="matrix">the matrix to initialize</param>
/// <param name="mean">the mean of the normal distribution drawn from</param>
/// <param name="stddev">the standard deviation of the normal distribution</param>
public static void InitNormal(this Matrix<float> matrix, double mean, double stddev)
{
var nd = new Normal(mean, stddev);
nd.RandomSource = Util.Random.GetInstance();
for (int i = 0; i < matrix.dim1; i++)
for (int j = 0; j < matrix.dim2; j++)
matrix[i, j] = (float) nd.Sample();
}
示例15: Run
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1
var normal = new Normal(0, 1);
Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", normal);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples
Console.WriteLine(@"3. Generate 10 samples");
for (var i = 0; i < 10; i++)
{
Console.Write(normal.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = normal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram");
normal.Mean = -10;
normal.StdDev = 0.01;
for (var i = 0; i < data.Length; i++)
{
data[i] = normal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}