|
| 1 | +# This file is part of TextClassification.jl |
| 2 | + |
| 3 | +export LIBSVMConfig, LIBSVMConfigSpace |
| 4 | + |
| 5 | +using LIBSVM |
| 6 | + |
| 7 | +@with_kw struct LIBSVMConfig |
| 8 | + C::Float64 = 1.0 |
| 9 | + weights = :balance |
| 10 | +end |
| 11 | + |
| 12 | +struct LIBSVMWrapper{LIBSVMModel} |
| 13 | + dim::Int |
| 14 | + cls::LIBSVMModel |
| 15 | +end |
| 16 | + |
| 17 | +function balanced_weights(y) |
| 18 | + C = countmap(y) |
| 19 | + s = sum(values(C)) |
| 20 | + nc = length(C) |
| 21 | + Dict{Any,Float64}(label => (s / (nc * count)) for (label, count) in C) |
| 22 | +end |
| 23 | + |
| 24 | +function create(config::LIBSVMConfig, train_X, train_y, dim) |
| 25 | + train_X_ = sparse(train_X, dim) |
| 26 | + nt = Threads.nthreads() |
| 27 | + verbose = true |
| 28 | + kernel = Kernel.Linear |
| 29 | + weights = balanced_weights(train_y) |
| 30 | + cls = svmtrain(train_X_, train_y; nt, weights, verbose, kernel, cost=config.C, ) |
| 31 | + LIBSVMWrapper(dim, cls) |
| 32 | +end |
| 33 | + |
| 34 | +@with_kw struct LIBSVMConfigSpace <: AbstractSolutionSpace |
| 35 | + C = [1.0] |
| 36 | + eps = [0.1] |
| 37 | + weights = [:balance, nothing] |
| 38 | + scale_C = (lower=0.001, s=3.0, upper=1000.0) |
| 39 | + scale_eps = (lower=0.0001, s=3.0, upper=0.99) |
| 40 | +end |
| 41 | + |
| 42 | +Base.eltype(::LIBSVMConfigSpace) = LIBSVMConfig |
| 43 | + |
| 44 | +function Base.rand(space::LIBSVMConfigSpace) |
| 45 | + LIBSVMConfig(rand(space.C), rand(space.weights)) |
| 46 | +end |
| 47 | + |
| 48 | +function combine(a::LIBSVMConfig, b::LIBSVMConfig) |
| 49 | + LIBSVMConfig(a.C, rand([a.weights, b.weights])) |
| 50 | +end |
| 51 | + |
| 52 | +function mutate(space::LIBSVMConfigSpace, a::LIBSVMConfig, iter) |
| 53 | + C = space.scale_C === nothing ? a.C : SearchModels.scale(a.C; space.scale_C...) |
| 54 | + weights = rand([a.weights, rand(space.weights)]) |
| 55 | + LIBSVMConfig(C, weights) |
| 56 | +end |
| 57 | + |
| 58 | +function predict(w::LIBSVMWrapper, vec::SVEC) |
| 59 | + ypred = svmpredict(w.cls, sparse([vec], w.dim); nt=Threads.nthreads()) |
| 60 | + ypred[1][1] |
| 61 | +end |
0 commit comments