|
| 1 | +package org.mikrograd.data.generator |
| 2 | + |
| 3 | +import kotlin.math.cos |
| 4 | +import kotlin.math.sin |
| 5 | +import kotlin.random.Random |
| 6 | + |
| 7 | +fun makeMoons( |
| 8 | + nSamples: Any = 100, |
| 9 | + shuffle: Boolean = true, |
| 10 | + noise: Double? = null, |
| 11 | + randomState: Int? = null |
| 12 | +): Pair<Array<DoubleArray>, IntArray> { |
| 13 | + val (nSamplesOut, nSamplesIn) = when (nSamples) { |
| 14 | + is Int -> Pair(nSamples / 2, nSamples - nSamples / 2) |
| 15 | + is Pair<*, *> -> { |
| 16 | + if (nSamples.first is Int && nSamples.second is Int) { |
| 17 | + Pair(nSamples.first as Int, nSamples.second as Int) |
| 18 | + } else { |
| 19 | + throw IllegalArgumentException("`n_samples` can be either an int or a two-element tuple.") |
| 20 | + } |
| 21 | + } |
| 22 | + else -> throw IllegalArgumentException("`n_samples` can be either an int or a two-element tuple.") |
| 23 | + } |
| 24 | + |
| 25 | + val generator = randomState?.let { Random(it) } ?: Random.Default |
| 26 | + |
| 27 | + val outerCircX = DoubleArray(nSamplesOut) { cos(it * Math.PI / nSamplesOut) } |
| 28 | + val outerCircY = DoubleArray(nSamplesOut) { sin(it * Math.PI / nSamplesOut) } |
| 29 | + val innerCircX = DoubleArray(nSamplesIn) { 1 - cos(it * Math.PI / nSamplesIn) } |
| 30 | + val innerCircY = DoubleArray(nSamplesIn) { 1 - sin(it * Math.PI / nSamplesIn) - 0.5 } |
| 31 | + |
| 32 | + val X = Array(nSamplesOut + nSamplesIn) { DoubleArray(2) } |
| 33 | + for (i in 0 until nSamplesOut) { |
| 34 | + X[i][0] = outerCircX[i] |
| 35 | + X[i][1] = outerCircY[i] |
| 36 | + } |
| 37 | + for (i in 0 until nSamplesIn) { |
| 38 | + X[nSamplesOut + i][0] = innerCircX[i] |
| 39 | + X[nSamplesOut + i][1] = innerCircY[i] |
| 40 | + } |
| 41 | + |
| 42 | + val y = IntArray(nSamplesOut + nSamplesIn) |
| 43 | + for (i in 0 until nSamplesOut) { |
| 44 | + y[i] = 0 |
| 45 | + } |
| 46 | + for (i in 0 until nSamplesIn) { |
| 47 | + y[nSamplesOut + i] = 1 |
| 48 | + } |
| 49 | + |
| 50 | + if (shuffle) { |
| 51 | + val indices = X.indices.toList().shuffled(generator) |
| 52 | + val XShuffled = Array(X.size) { DoubleArray(2) } |
| 53 | + val yShuffled = IntArray(y.size) |
| 54 | + for (i in indices.indices) { |
| 55 | + XShuffled[i] = X[indices[i]] |
| 56 | + yShuffled[i] = y[indices[i]] |
| 57 | + } |
| 58 | + X.indices.forEach { X[it] = XShuffled[it] } |
| 59 | + y.indices.forEach { y[it] = yShuffled[it] } |
| 60 | + } |
| 61 | + |
| 62 | + noise?.let { |
| 63 | + for (i in X.indices) { |
| 64 | + X[i][0] += generator.nextDouble(-noise, noise) |
| 65 | + X[i][1] += generator.nextDouble(-noise, noise) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return Pair(X, y) |
| 70 | +} |
| 71 | + |
0 commit comments