I am trying to put into place some code that will do the same as Python, Numpy.random.Choice
The critical part is: probability
The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.
Some Test Code:
import numpy as np
n = 5
vocab_size = 3
p = np.array( [[ 0.65278451], [ 0.0868038725], [ 0.2604116175]])
print('Sum: ', repr(sum(p)))
for t in range(n):
x = np.random.choice(range(vocab_size), p=p.ravel())
print('x: %s x[x]: %s' % (x, p.ravel()[x]))
print(p.ravel())
This gives an output of:
Sum: array([ 1.])
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
[ 0.65278451 0.08680387 0.26041162]
Sometimes.
There is a Distribution here, and it is a partially Random one, but there is also Structure there.
I want to implement this in C#, and to be honest, I am not sure on an efficient way to do it.
Some 4 Years ago there was a good question asked: Emulate Python's random.choice in .NET
Being this is quite old now and also does not really go into depth on the uniform probability distribution, I thought I would ask for some elaboration?
Now times have changed and Code is changing, I think there may be a better way to implement a .NET Random.Choice() Method.
public static int Choice(Vector sequence, int a = 0, int size = 0, bool replace = false)
{
// F(x)
var Fx = 1/(b - a)
var p = (xmax - xmin) * Fx
return random.Next(0, sequence.Length);
}
Vector is only a double[].
How would I go about randomly Choosing a Probability from a Vector like so:
p = np.array(
[[ 0.01313731], [ 0.01315883], [ 0.01312814], [ 0.01316345], [ 0.01316839],
[ 0.01314225], [ 0.01317578], [ 0.01312916], [ 0.01316344], [ 0.01317046],
[ 0.01314973], [ 0.01314432], [ 0.01317042], [ 0.01314846], [ 0.01315124],
[ 0.01316694], [ 0.0131816 ], [ 0.01315033], [ 0.0131645 ], [ 0.01314199],
[ 0.01315199], [ 0.01314431], [ 0.01314458], [ 0.01314999], [ 0.01315409],
[ 0.01316245], [ 0.01315008], [ 0.01314104], [ 0.01315215], [ 0.01317024],
[ 0.01315993], [ 0.01318789], [ 0.0131677 ], [ 0.01316761], [ 0.01315658],
[ 0.01315902], [ 0.01314266], [ 0.0131637 ], [ 0.01315702], [ 0.01315776],
[ 0.01316194], [ 0.01316246], [ 0.01314769], [ 0.01315608], [ 0.01315487],
[ 0.01316117], [ 0.01315083], [ 0.01315836], [ 0.0131665 ], [ 0.01314706],
[ 0.01314923], [ 0.01317971], [ 0.01316373], [ 0.01314863], [ 0.01315498],
[ 0.01315732], [ 0.01318195], [ 0.01315505], [ 0.01315979], [ 0.01315992],
[ 0.01316072], [ 0.01314744], [ 0.0131638 ], [ 0.01315642], [ 0.01314933],
[ 0.01316188], [ 0.01315458], [ 0.01315551], [ 0.01317907], [ 0.01316296],
[ 0.01317765], [ 0.01316863], [ 0.01316804], [ 0.01314882], [ 0.01316548],
[ 0.01315487]])
The Output in Python is:
Sum: array([ 1.])
x: 21 x[x]: 0.01314431
x: 30 x[x]: 0.01315993
x: 54 x[x]: 0.01315498
x: 31 x[x]: 0.01318789
x: 27 x[x]: 0.01314104
Sometimes.
Aucun commentaire:
Enregistrer un commentaire