|
| 1 | +module Argmax |
| 2 | + |
| 3 | +using ..Utils |
| 4 | +using DocStringExtensions: TYPEDEF, TYPEDFIELDS, TYPEDSIGNATURES |
| 5 | +using Flux: Chain, Dense |
| 6 | +using Random |
| 7 | + |
| 8 | +""" |
| 9 | +$TYPEDEF |
| 10 | +
|
| 11 | +Benchmark problem with an argmax as the CO algorithm. |
| 12 | +
|
| 13 | +# Fields |
| 14 | +$TYPEDFIELDS |
| 15 | +""" |
| 16 | +struct ArgmaxBenchmark <: AbstractBenchmark |
| 17 | + "iinstances dimension, total number of classes" |
| 18 | + instance_dim::Int |
| 19 | + "number of features" |
| 20 | + nb_features::Int |
| 21 | +end |
| 22 | + |
| 23 | +function Base.show(io::IO, bench::ArgmaxBenchmark) |
| 24 | + (; instance_dim, nb_features) = bench |
| 25 | + return print( |
| 26 | + io, "ArgmaxBenchmark(instance_dim=$instance_dim, nb_features=$nb_features)" |
| 27 | + ) |
| 28 | +end |
| 29 | + |
| 30 | +function ArgmaxBenchmark(; instance_dim::Int=10, nb_features::Int=5) |
| 31 | + return ArgmaxBenchmark(instance_dim, nb_features) |
| 32 | +end |
| 33 | + |
| 34 | +""" |
| 35 | +$TYPEDSIGNATURES |
| 36 | +
|
| 37 | +One-hot encoding of the argmax function. |
| 38 | +""" |
| 39 | +function one_hot_argmax(z::AbstractVector{R}; kwargs...) where {R<:Real} |
| 40 | + e = zeros(R, length(z)) |
| 41 | + e[argmax(z)] = one(R) |
| 42 | + return e |
| 43 | +end |
| 44 | + |
| 45 | +""" |
| 46 | +$TYPEDSIGNATURES |
| 47 | +
|
| 48 | +Return a top k maximizer. |
| 49 | +""" |
| 50 | +function Utils.generate_maximizer(bench::ArgmaxBenchmark) |
| 51 | + return one_hot_argmax |
| 52 | +end |
| 53 | + |
| 54 | +""" |
| 55 | +$TYPEDSIGNATURES |
| 56 | +
|
| 57 | +Generate a dataset of labeled instances for the subset selection problem. |
| 58 | +The mapping between features and cost is identity. |
| 59 | +""" |
| 60 | +function Utils.generate_dataset(bench::ArgmaxBenchmark, dataset_size::Int=10; seed::Int=0) |
| 61 | + (; instance_dim, nb_features) = bench |
| 62 | + rng = MersenneTwister(seed) |
| 63 | + features = [randn(rng, Float32, nb_features, instance_dim) for _ in 1:dataset_size] |
| 64 | + mapping = Chain(Dense(nb_features => 1; bias=false), vec) |
| 65 | + costs = mapping.(features) |
| 66 | + solutions = one_hot_argmax.(costs) |
| 67 | + return [ |
| 68 | + DataSample(; x, θ_true, y_true) for |
| 69 | + (x, θ_true, y_true) in zip(features, costs, solutions) |
| 70 | + ] |
| 71 | +end |
| 72 | + |
| 73 | +""" |
| 74 | +$TYPEDSIGNATURES |
| 75 | +
|
| 76 | +Initialize a linear model for `bench` using `Flux`. |
| 77 | +""" |
| 78 | +function Utils.generate_statistical_model(bench::ArgmaxBenchmark; seed=0) |
| 79 | + Random.seed!(seed) |
| 80 | + (; nb_features) = bench |
| 81 | + return Chain(Dense(nb_features => 1; bias=false), vec) |
| 82 | +end |
| 83 | + |
| 84 | +export ArgmaxBenchmark |
| 85 | + |
| 86 | +end |
0 commit comments