Stupid question, but how exactly can we use NormalDistribution
to generate an array of random numbers? The doc indicates the next method takes what I assume is a RandomNumberGenerator (for rng) but I haven’t figured out how to pass it properly yet.
A simple example would be much appreciated!
1 Like
This seems to work:
import TensorFlow
var rng = ARC4RandomNumberGenerator(seed: UInt64(1))
let dist = NormalDistribution<Double>(mean: 0, standardDeviation: 1)
var numbers: [Double] = []
let len = 1000
for _ in 0 ..< len {
numbers.append(dist.next(using: &rng))
}
print(numbers)
Looked up in unit tests https://github.com/tensorflow/swift-apis/blob/ff93c7e70f53bc065082da3f3fab7fae8f5f9455/Tests/DeepLearningTests/PRNGTests.swift#L108
2 Likes
The RandomDistribution
protocol (which NormalDistribution
and other distributions conform to) is pretty barebones right now. For now, you can use sth like the following:
import TensorFlow
extension RandomDistribution {
// Returns a batch of samples.
func next<G: RandomNumberGenerator>(
_ count: Int, using generator: inout G
) -> [Sample] {
var result: [Sample] = []
for _ in 0..<count {
result.append(next(using: &generator))
}
return result
}
// Returns a batch of samples, using the global Threefry RNG.
func next(_ count: Int) -> [Sample] {
return next(count, using: &ThreefryRandomNumberGenerator.global)
}
}
let dist = NormalDistribution<Float>(mean: 100, standardDeviation: 10)
print(dist.next(5))
// [98.81818, 110.83851, 103.91379, 100.8439, 100.6089]
5 Likes
Thank you both!
@vova I was in the code source and it never occurred to me to go look at the tests, will remember next time.
1 Like