licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
2722
import BenchPerfConfigSweeps using DataFrames using VegaLite sweepresult = BenchPerfConfigSweeps.load(joinpath(@__DIR__, "build")) df_raw = DataFrame(sweepresult) let global df = select(df_raw, Not(:trial)) df[:, :time_ns] = map(t -> minimum(t.benchmark).time, df_raw.trial) df[:, :evals] = map(t -> t.benchmark.params.evals, df_raw.trial) df[:, :L1_miss_percent] = map(df_raw.trial) do t t.perf["L1-dcache-load-misses"] / t.perf["L1-dcache-loads"] * 100 end df[:, :LL_miss_percent] = map(df_raw.trial) do t get(t.perf, "LLC-load-misses", missing) / get(t.perf, "LLC-loads", missing) * 100 end bytes = df.n .* 2 * sizeof(Int) global throughput_unit = "GiB/sec" df[:, :throughput] = bytes ./ 2^30 ./ (df.time_ns / 1e9) df[:, :MiB] = bytes ./ 2^20 df[:, :total_MiB] = bytes ./ 2^20 df end plt_throughput_cache_miss = @vlplot( vconcat = [ { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, }, { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, }, { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, }, ], data = df, ) # TODO: include LLC access rate @vlplot( vconcat = [ { layer = [ { mark = {:line, point = true}, encoding = { x = {:n, scale = {type = :log}}, y = {:evals, scale = {type = :log}}, }, }, { # A vertical line above which (`n >=`) benchmarks are not # tuned. mark = :rule, encoding = {x = {datum = 2^15}}, }, ], }, { encoding = {x = {:MiB, scale = {type = :log}}}, layer = [ { mark = {:line, point = true}, encoding = {y = {:evals, scale = {type = :log}}}, }, { mark = {:line, color = "#85C5A6"}, y = { :throughput, title = throughput_unit, axis = {titleColor = "#85C5A6"}, }, }, ], resolve = {scale = {y = :independent}}, }, ], data = df, ) plt_throughput_cache_miss
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
174
using BenchmarkConfigSweeps BenchmarkConfigSweeps.run( joinpath(@__DIR__, "build"), joinpath(@__DIR__, "benchmarks.jl"), BenchmarkConfigSweeps.nthreads.([1]), )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
943
import BenchPerf import Random using BenchmarkTools @noinline function sum_gather(xs, indices) s = zero(eltype(xs)) for i in indices s += @inbounds xs[i] end return s end CACHE = Dict() group = BenchmarkGroup() for e in 5:22 n = 2^e CACHE[e] = (xs = zeros(Int, n), indices = rand(1:n, n)) group["n=$n"] = bench = @benchmarkable( sum_gather(xs, indices), setup = begin inputs = CACHE[$e]::$(typeof(CACHE[e])) xs = inputs.xs indices = inputs.indices fill!(xs, 0) end, # Larger `samples` (than the default: 10_000) to bound the benchmark by # the time limit. samples = 1_000_000, ) # Manually tune the benchmark since `BenchmarkConfigSweeps` does not do it # ATM. if e < 15 tune!(bench) end end include("../quick.jl") maybe_quick!(group) SUITE = BenchPerf.wrap(group; detailed = 1)
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
3252
import BenchPerfConfigSweeps import DisplayAs using DataFrames using VegaLite sweepresult = BenchPerfConfigSweeps.load(joinpath(@__DIR__, "build")) df_raw = DataFrame(sweepresult) let global df = select(df_raw, Not(:trial)) df[:, :time_ns] = map(t -> minimum(t.benchmark).time, df_raw.trial) df[:, :evals] = map(t -> t.benchmark.params.evals, df_raw.trial) df[:, :L1_miss_percent] = map(df_raw.trial) do t t.perf["L1-dcache-load-misses"] / t.perf["L1-dcache-loads"] * 100 end df[:, :LL_miss_percent] = map(df_raw.trial) do t get(t.perf, "LLC-load-misses", missing) / get(t.perf, "LLC-loads", missing) * 100 end bytes = df.n .* 2 * sizeof(Int) global throughput_unit = "GiB/sec" df[:, :throughput] = bytes ./ 2^30 ./ (df.time_ns / 1e9) df[:, :MiB] = bytes ./ 2^20 df[:, :total_MiB] = bytes ./ 2^20 df end resultdir = joinpath(@__DIR__, "result") mkpath(resultdir) saveresult(; plots...) = saveresult(:png, :svg; plots...) function saveresult(exts::Symbol...; plots...) for (k, v) in plots for e in exts save(joinpath(resultdir, "$k.$e"), v) end end end nothing # hide plt_throughput_cache_miss = @vlplot( vconcat = [ { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, }, { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, }, { mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, }, ], data = df, ) saveresult(; plt_throughput_cache_miss) plt_throughput_cache_miss plt_throughput_cache_miss |> DisplayAs.PNG # TODO: include LLC access rate # ## Tuned `evals` plt_evals = @vlplot( vconcat = [ { layer = [ { mark = {:line, point = true}, encoding = { x = {:n, scale = {type = :log}}, y = {:evals, scale = {type = :log}}, }, }, { # A vertical line above which (`n >=`) benchmarks are not # tuned. mark = :rule, encoding = {x = {datum = 2^15}}, }, ], }, { encoding = {x = {:MiB, scale = {type = :log}}}, layer = [ { mark = {:line, point = true}, encoding = {y = {:evals, scale = {type = :log}}}, }, { mark = {:line, color = "#85C5A6"}, y = { :throughput, title = throughput_unit, axis = {titleColor = "#85C5A6"}, }, }, ], resolve = {scale = {y = :independent}}, }, ], data = df, ) saveresult(; plt_evals) plt_evals plt_evals |> DisplayAs.PNG #- plt_throughput_cache_miss #src
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
240
# # Single-thread `sum_gather` include("plots.jl"); # ## Throughput, L1, and last-level (LL) cache misses # # (Note: the LL cache miss data may not be available in some machines.) plt_throughput_cache_miss # ## Tuned `evals` plt_evals
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
174
using BenchmarkConfigSweeps BenchmarkConfigSweeps.run( joinpath(@__DIR__, "build"), joinpath(@__DIR__, "benchmarks.jl"), BenchmarkConfigSweeps.nthreads.([1]), )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
165
using Literate include("../literate_utlis.jl") Literate.notebook( joinpath(@__DIR__, "report.jl"), @__DIR__; preprocess = preprocess_natural_comment, )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
534
baremodule BenchPerfConfigSweeps function load end # function simpletable end # function flattable end module Internal import BenchPerf import BenchmarkConfigSweeps using BenchmarkTools: BenchmarkTools, BenchmarkGroup # TODO: Turn these to public API? using BenchPerf.Internal: GroupPerf, GroupResult, TrialPerf, TrialResult using BenchmarkConfigSweeps.Internal: SweepResult, resultpath using ..BenchPerfConfigSweeps: BenchPerfConfigSweeps include("internal.jl") end # module Internal end # baremodule BenchPerfConfigSweeps
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1219
function BenchPerfConfigSweeps.load(resultdir) sweep = BenchmarkConfigSweeps.load(resultdir) perfs = Vector{Union{GroupPerf,Nothing}}(undef, length(sweep.results)) fill!(perfs, nothing) for (i, r) in enumerate(sweep.results) if r !== nothing perfpath = BenchPerf.perfpath(resultpath(resultdir, i)) perfs[i] = BenchPerf.loadperf(perfpath) end end replacetrials!(sweep.results, perfs) return sweep # return BenchPerfSweepResult(sweep, perfs) end # struct BenchPerfSweepResult # sweep::SweepResult # perfs::Vector{Union{GroupPerf,Nothing}} # end function replacetrials!(results::AbstractVector, perfs::AbstractVector) @assert axes(results) == axes(perfs) for (r, p) in zip(results, perfs) r === nothing && continue @assert p !== nothing replacetrials!(r, p) end return results end function replacetrials!(bench::BenchmarkGroup, perf::GroupPerf) @assert issetequal(keys(bench), keys(perf)) for (k, bv) in bench pv = perf[k] bench[k] = replacetrials!(bv, pv) end return bench end replacetrials!(bench::BenchmarkTools.Trial, perf::TrialPerf) = TrialResult(bench, perf)
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
582
baremodule BenchPerf function run end # function save end # function load end function perfpath end function loadperf end function wrap end module Internal import JSON import PrettyTables import Tables using BenchmarkTools if !isdefined(@__MODULE__, Symbol("@something")) using Compat: @something const USE_COMPAT = true else const USE_COMPAT = false end using ..BenchPerf: BenchPerf include("perf.jl") include("execution.jl") include("wrap.jl") include("accessors.jl") include("show.jl") include("tables.jl") end # module Internal end # baremodule BenchPerf
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
2865
const RATIO_TABLE = [ # (numerator, denominator)-pair ("branch-misses", "branches"), ("L1-dcache-load-misses", "L1-dcache-loads"), ("L1-icache-load-misses", "L1-icache-loads"), ("LLC-load-misses", "LLC-loads"), ("dTLB-load-misses", "dTLB-loads"), ("iTLB-load-misses", "iTLB-loads"), ("stalled-cycles-frontend", "cycles"), ("stalled-cycles-backend", "cycles"), ] const OTHER_KEYS = [ # "task-clock" TODO: float "context-switches", "cpu-migrations", "page-faults", "instructions", ] as_property_symbol(str::AbstractString) = Symbol(lowercase(replace(str, "-" => "_"))) const ALL_KEYS = unique!(vcat(first.(RATIO_TABLE), last.(RATIO_TABLE), OTHER_KEYS)) for key in ALL_KEYS val = Val{as_property_symbol(key)} @eval getvalue(t::TrialPerf, ::$val)::Union{Int,Nothing} = @something(get(t, $key, nothing), return) end for (num, den) in RATIO_TABLE numval = Val{as_property_symbol(num)} denval = Val{as_property_symbol(den)} @eval function getratio(t::TrialPerf, ::$numval)::Union{Float64,Nothing} num = @something(getvalue(t, $numval()), return) den = @something(getvalue(t, $denval()), return) return num / den end end # perf calls them (and the ratios) "shaddow stats" const DERIVED_NAMES = [ :instructions_per_cycle, # "insn per cycle" :stalled_cycles_per_instructions, # "stalled cycles per insn" ] const ALL_NAMES = (as_property_symbol.(ALL_KEYS)..., DERIVED_NAMES...) const RATIO_NAMES = (as_property_symbol.(first.(RATIO_TABLE))...,) struct RatioAccessor trial::TrialPerf end struct PercentAccessor trial::TrialPerf end Base.getproperty(accessor::RatioAccessor, name::Symbol) = getratio(getfield(accessor, :trial), Val{name}()) Base.getproperty(accessor::PercentAccessor, name::Symbol) = @something(getratio(getfield(accessor, :trial), Val{name}()), return) * 100 function Base.propertynames( accessor::Union{RatioAccessor,PercentAccessor}, private::Bool = false, ) pubnames = RATIO_NAMES if private return (pubnames..., fieldnames(typeof(accessor))) else return pubnames end end getratio(::TrialPerf, @nospecialize(_val::Val{name})) where {name} = error(name, " is not a name of suportd ratio ", RATIO_NAMES) function getvalue(trial::TrialPerf, ::Val{:instructions_per_cycle}) num = @something(trial.instructions, return) den = @something(trial.cycles, return) return num / den end # https://github.com/torvalds/linux/blob/v5.15/tools/perf/util/stat-shadow.c#L979-L991 function getvalue(trial::TrialPerf, ::Val{:stalled_cycles_per_instructions}) f = @something(trial.stalled_cycles_frontend, return) b = @something(trial.stalled_cycles_backend, return) num = max(f, b) den = @something(trial.instructions, return) return num / den end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1058
struct TrialResult benchmark::BenchmarkTools.Trial perf::TrialPerf end struct GroupResult benchmark::BenchmarkGroup perf::GroupPerf end as_result(b::BenchmarkTools.Trial, p::TrialPerf) = TrialResult(b, p) as_result(b::BenchmarkGroup, p::GroupPerf) = GroupResult(b, p) function BenchPerf.run(bench_or_group; verbose = false, kwargs...) cfg = as_perf_config(; kwargs...) b, p = execute(bench_or_group, cfg, (; verbose = verbose)) return as_result(b, p) end _isverbose(; verbose = false, _ignore...) = verbose execute(b::BenchmarkTools.Benchmark, cfg::PerfConfig, runopts, _level = 0) = withperf(() -> run(b; runopts...), cfg) function execute(g::BenchmarkGroup, cfg::PerfConfig, runopts, level = 0) n = length(g) benchresult = similar(g) perfresult = GroupPerf() for (i, (k, v)) in enumerate(pairs(g)) _isverbose(; runopts...) && println(stderr, " "^level, "[$i/$n] ", k) benchresult[k], perfresult[k] = execute(v, cfg, runopts, level + 1) end return (benchresult, perfresult) end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
5250
# TODO: Use LinuxPerf.jl after https://github.com/JuliaPerf/LinuxPerf.jl/pull/22 struct PerfConfig detailed::Int event::Union{Nothing,String} per_thread::Bool all_cpus::Bool cpu::Union{Nothing,String} _perfopts::Cmd # (for easily trying new options) TODO: remove this end function as_perf_config(; detailed::Union{Integer,Nothing} = nothing, event::Union{AbstractVector{<:AbstractString},Nothing} = nothing, per_thread::Bool = false, cpu::Union{AbstractString,Nothing} = nothing, all_cpus::Bool = cpu !== nothing, _perfopts::Cmd = ``, ) if detailed === nothing detailed = 0 elseif detailed < 0 error("`detailed` must be 1, 2, or 3") end if event !== nothing event = join(event, ",") end return PerfConfig(detailed, event, per_thread, all_cpus, cpu, _perfopts) end const CacheDict = Dict{String,Union{Float64,Int}} const CacheRef = Ref{Union{Nothing,CacheDict}} struct TrialPerf output::String cache::CacheRef end TrialPerf(output) = TrialPerf(output, CacheRef(nothing)) JSON.lower(t::TrialPerf) = (; output = getfield(t, :output)) struct GroupPerf group::Dict{Any,Union{TrialPerf,GroupPerf}} end const GenericPerf = Union{TrialPerf,GroupPerf} GroupPerf() = GroupPerf(Dict{Any,GenericPerf}()) Base.keys(g::GroupPerf) = keys(g.group) Base.get(g::GroupPerf, k, default) = get(g.group, k, default) Base.getindex(g::GroupPerf, k) = g.group[k] Base.setindex!(g::GroupPerf, v::GenericPerf, k) = g.group[k] = v const FIELD_SEPARATOR = '\\' # as recommended in perf-stat(1) function Base.Cmd(cfg::PerfConfig) cmd = `perf stat` if cfg.detailed > 0 detailed = "-" * "d"^cfg.detailed cmd = `$cmd $detailed` end if cfg.event !== nothing cmd = `$cmd --event=$(cfg.event)` end if cfg.per_thread cmd = `$cmd --per-thread` end cmd = `$cmd $(cfg._perfopts)` cmd = `$cmd --field-separator=$FIELD_SEPARATOR` if cfg.all_cpus cmd = `$cmd --all-cpus` if cfg.cpu !== nothing cmd = `$cmd --cpu=$(cfg.cpu)` end else cmd = `$cmd --pid=$(getpid())` end return cmd end function withperf(f, cfg::PerfConfig) cmd = Cmd(cfg) output = Ref{String}() outpipe = Pipe() proc = run(pipeline(cmd, stdout = stderr, stderr = outpipe); wait = false) local y @sync begin try close(outpipe.in) @async output[] = read(outpipe, String) y = f() catch close(outpipe) rethrow() finally @debug "Stopping perf:" cmd flush(stderr) kill(proc, Base.SIGINT) wait(proc) end end return (y, TrialPerf(output[])) end function getcache(trial::TrialPerf) ref = getfield(trial, :cache) cache = ref[] if cache === nothing ref[] = cache = parsestat(getfield(trial, :output)) end return cache end function parsestat(output) cache = CacheDict() for ln in eachline(IOBuffer(output)) parts = split(ln, FIELD_SEPARATOR) isempty(parts[1]) && continue k = parts[3] parts[1] == "<not supported>" && continue v = tryparse(Int, parts[1]) if v === nothing v = tryparse(Float64, parts[1]) if v === nothing error("failed parsing row: ", ln) end end cache[k] = v end return cache end Base.keys(trial::TrialPerf) = keys(getcache(trial)) Base.get(trial::TrialPerf, key, default) = get(getcache(trial), key, default) Base.getindex(trial::TrialPerf, event::AbstractString) = getcache(trial)[event] function Base.propertynames(::TrialPerf, private::Bool = false) pubnames = (ALL_NAMES..., :ratio, :percent) if private return (pubnames..., fieldnames(TrialPerf)) else return pubnames end end function Base.getproperty(trial::TrialPerf, name::Symbol) if name in ALL_NAMES return getvalue(trial, Val{name}()) elseif name === :ratio return RatioAccessor(trial) elseif name === :percent return PercentAccessor(trial) else return getfield(trial, name) end end fulltable(trial::TrialPerf) = fulltable(trial.output) function fulltable(output::AbstractString) table = ( value = Union{Float64,Int64,Nothing}[], unit = Union{String,Nothing}[], event = String[], runtime = Union{Int64,Nothing}[], percentage = Union{Float64,Nothing}[], optional_metric = Union{Float64,Nothing}[], optional_unit = Union{String,Nothing}[], ) for ln in eachline(IOBuffer(output)) parts = split(ln, FIELD_SEPARATOR) push!( table.value, something(tryparse(Int, parts[1]), tryparse(Float64, parts[1]), Some(nothing)), ) push!(table.unit, isempty(parts[2]) ? nothing : parts[2]) push!(table.event, parts[3]) push!(table.runtime, tryparse(Int64, parts[4])) push!(table.percentage, tryparse(Float64, parts[5])) push!(table.optional_metric, tryparse(Float64, parts[6])) push!(table.optional_unit, parts[7]) end return table end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
403
function Base.show(io::IO, ::MIME"text/plain", trial::TrialPerf) PrettyTables.pretty_table(io, trial) end function Base.show(io::IO, ::MIME"text/plain", trial::TrialResult) show(io, MIME"text/plain"(), trial.benchmark) println(io) lines, columns = displaysize(io) lines = max(128, lines) show(IOContext(io, :displaysize => (lines, columns)), MIME"text/plain"(), trial.perf) end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
159
Tables.istable(::Type{TrialPerf}) = true Tables.columnaccess(::Type{TrialPerf}) = true Tables.columns(perf::TrialPerf) = Tables.CopiedColumns(fulltable(perf))
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1530
struct BenchmarkWrapper benchmark::BenchmarkTools.Benchmark cfg::PerfConfig end struct GroupWrapper benchmark::BenchmarkGroup cfg::PerfConfig end BenchPerf.wrap(b::BenchmarkTools.Benchmark; kwargs...) = BenchmarkWrapper(b, as_perf_config(; kwargs...)) BenchPerf.wrap(b::BenchmarkGroup; kwargs...) = GroupWrapper(b, as_perf_config(; kwargs...)) function Base.run(bp::Union{BenchmarkWrapper,GroupWrapper}; runopts...) b, p = execute(bp.benchmark, bp.cfg, runopts) return as_result(b, p) end function BenchPerf.perfpath(filepath::AbstractString) if endswith(filepath, ".json") return filepath[1:end-length(".json")] * "-perf.json" else error("Result `filepath` must have `.json` extension; got: ", filepath) end end function BenchmarkTools.save(filepath::AbstractString, result::GroupResult) perfpath = BenchPerf.perfpath(filepath) BenchmarkTools.save(filepath, result.benchmark) open(perfpath, write = true) do io JSON.print(io, result.perf) end return end BenchPerf.loadperf(perfpath) = from_json(JSON.parsefile(perfpath)) function from_json(d::Dict{String,Any}) if (group = get(d, "group", nothing)) !== nothing group = group::Dict{String,Any} perf = GroupPerf() for (k, v) in group perf[k] = from_json(v) end return perf elseif (output = get(d, "output", nothing)) !== nothing return TrialPerf(output) else error("unrecognized dictionary: ", d) end end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
49
using TestFunctionRunner TestFunctionRunner.@run
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
133
module BenchPerfTests include("test_parsing.jl") include("test_accessors.jl") include("test_aqua.jl") end # module BenchPerfTests
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1618
module TestAccessors using Test using ..TestParsing: load_sample function test_default() perf = load_sample("default") @test perf.context_switches == 124 @test perf.cpu_migrations == 0 @test perf.page_faults == 92541 @test perf.cycles == 3410157225 @test perf.stalled_cycles_frontend == 74012542 @test perf.stalled_cycles_backend == 1498764411 @test perf.instructions == 5107038786 @test perf.instructions_per_cycle ≈ 1.5 rtol = 0.005 @test perf.stalled_cycles_per_instructions ≈ 0.29 atol = 0.005 @test perf.ratio.stalled_cycles_frontend == 74012542 / 3410157225 @test perf.ratio.stalled_cycles_backend == 1498764411 / 3410157225 end function test_d1_with_llc() perf = load_sample("d1-with-llc") @test perf.branches == 402774448 @test perf.branch_misses == 6375125 @test perf.l1_dcache_loads == 650213241 @test perf.l1_dcache_load_misses == 19264237 @test perf.l1_icache_loads === nothing @test perf.l1_icache_load_misses === nothing @test perf.llc_loads == 2029190 @test perf.llc_load_misses == 1158158 @test perf.ratio.branch_misses == 6375125 / 402774448 @test perf.ratio.l1_dcache_load_misses == 19264237 / 650213241 @test perf.ratio.l1_icache_load_misses === nothing @test perf.ratio.llc_load_misses == 1158158 / 2029190 @test perf.percent.branch_misses == 6375125 / 402774448 * 100 @test perf.percent.l1_dcache_load_misses == 19264237 / 650213241 * 100 @test perf.percent.l1_icache_load_misses === nothing @test perf.percent.llc_load_misses == 1158158 / 2029190 * 100 end end # module
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
256
module TestAqua import Aqua import BenchPerf test() = Aqua.test_all( BenchPerf; # Compat.jl is conditionally loaded: stale_deps = if BenchPerf.Internal.USE_COMPAT true else (; ignore = [:Compat]) end, ) end # module
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
746
module TestParsing import Tables using BenchPerf.Internal: TrialPerf using Test load_sample(name) = TrialPerf(read(joinpath(@__DIR__, "samples", name * ".csv"), String)) function load_samples() samples = Iterators.map(readdir(joinpath(@__DIR__, "samples"); join = true)) do path splitext(basename(path))[1] => TrialPerf(read(path, String)) end samples = Iterators.filter(!isnothing, samples) return Dict(samples) end function test_event_samples() @testset "$name" for (name, trial) in load_samples() @test !isempty(keys(trial)) end end function test_full_samples() @testset "$name" for (name, trial) in load_samples() @test !isempty(Tables.columns(trial).value) end end end # module
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
docs
94
# BenchPerf BenchPerf.jl can be used to collect `perf stat` measurements for each benchmark.
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.2
168adfc1319d0f98e60edcd3c476a273afedb699
code
703
using PlugFlowReactor using Documenter DocMeta.setdocmeta!(PlugFlowReactor, :DocTestSetup, :(using PlugFlowReactor); recursive=true) makedocs(; modules=[PlugFlowReactor], authors="Vinod Janardhanan", repo="https://github.com/vinodjanardhanan/PlugFlowReactor.jl/blob/{commit}{path}#{line}", sitename="PlugFlowReactor.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://vinodjanardhanan.github.io/PlugFlowReactor.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/vinodjanardhanan/PlugFlowReactor.jl", devbranch="main", )
PlugFlowReactor
https://github.com/vinodjanardhanan/PlugFlowReactor.jl.git
[ "MIT" ]
0.1.2
168adfc1319d0f98e60edcd3c476a273afedb699
code
12667
module PlugFlowReactor using LightXML, Printf, DifferentialEquations, Sundials using SurfaceReactions, GasphaseReactions, ReactionCommons, IdealGas, RxnHelperUtils export plug global os_streams """ This is the calling function for executing the plug reactor with userdefined rate calculation # Method-1 plug(input_file::AbstractString, lib_dir::AbstractString; sens= false, surfchem=false, gaschem=false) - input_file: the xml input file for batch reactor - lib_dir: the direcrtory in which the data files are present. It must be the relative path - user_defined: A function which calculates the species source terms, to be supplied by the user """ function plug(input_file::AbstractString, lib_dir::AbstractString, user_defined::Function; sens= false) chem = Chemistry(false, false, true, user_defined) return plug(input_file, lib_dir, sens, chem) end """ This is the calling function for executing the plug reactor with chemistry input files # Method-2 plug(input_file::AbstractString, lib_dir::AbstractString; sens= false, surfchem=false, gaschem=false) - input_file: the xml input file plug flow reactor configuration - lib_dir: the direcrtory in which the data files are present (mechanism file and therm.dat file). - sens: sensitivity calculation - surfchem : surface chemistry; false implies no surface chemistry calculation - gaschem : gasphase chemistry; false implies no gasphase chemistry calculation """ function plug(input_file::AbstractString, lib_dir::AbstractString; sens= false, surfchem=false, gaschem=false) chem = Chemistry(surfchem, gaschem, false, f->()) return plug(input_file, lib_dir, sens, chem) end #= This is the general iterface for starting the plug flow code by reading the input files. =# function plug(input_file::AbstractString, lib_dir::AbstractString, sens, chem::Chemistry) #locate the lib directory thermo_file = "therm.dat" thermo_file = get_path(lib_dir, thermo_file) local gasphase = Array{String,1} xmldoc = parse_file(input_file) xmlroot = root(xmldoc) """ In case the gasphase mechanism is present then the gasphase species are read from the gasphase mechanism file and not from the xml input. So this must be the first action before any other input parameters are read """ if chem.gaschem mech_file = get_text_from_xml(xmlroot,"gas_mech") mech_file = get_path(lib_dir, mech_file) gmd = compile_gaschemistry(mech_file) gasphase = gmd.gm.species end #Get gasphase species list from the xml input if !chem.gaschem gasphase = get_collection_from_xml(xmlroot,"gasphase") end thermo_obj = IdealGas.create_thermo(gasphase,thermo_file) #Get the molefractions mole_fracs = get_molefraction_from_xml(xmlroot, thermo_obj.molwt, gasphase) #Convert mole fractions to mass fractions mass_fracs = zeros( length(gasphase)) molefrac_to_massfrac!(mass_fracs,mole_fracs,thermo_obj.molwt) #Read the inlet temperature local T = get_value_from_xml(xmlroot,"T") #Read the velocity local u = get_value_from_xml(xmlroot,"u") #Read the pressure local p = get_value_from_xml(xmlroot,"p") #Read the length of the reactor local l = get_value_from_xml(xmlroot,"length") #Read the diameter of the reactor local dia = get_value_from_xml(xmlroot,"dia") local Ac = π*dia^2/4.0 local As_per_unit_length = π*dia #Read the wall temperature local Tw = get_value_from_xml(xmlroot,"Tw") #Read the surface area per unit length local cat_geom = get_value_from_xml(xmlroot,"cat-geom-factor") #Read the temperature condition isothermal = lowercase(get_text_from_xml(xmlroot,"isothermal")) == "true" ? true : false #Create the mechanism definition if chem.surfchem #Get the mechanism file from xml mech_file = get_text_from_xml(xmlroot,"surface_mech") # mech_file = lib_dir*"/"*mech_file mech_file = get_path(lib_dir, mech_file) md = SurfaceReactions.compile_mech(mech_file,thermo_obj,gasphase) end #create the soln vector soln = deepcopy(mass_fracs) #mass fractions push!(soln,density(mole_fracs,thermo_obj.molwt,T,p)*u) #mass flux ρu if !isothermal push!(soln,T) end #file output streams for saving the data g_stream = open(output_file(input_file, "gas_profile.dat"),"w") s_stream = open(output_file(input_file, "surf_covg.dat"),"w") csv_g_stream = open(output_file(input_file, "gas_profile.csv"),"w") csv_s_stream = open(output_file(input_file, "surf_covg.csv"),"w") global os_streams = (g_stream,s_stream, csv_g_stream, csv_s_stream) geometry = (Ac,As_per_unit_length,cat_geom) create_header(g_stream,["z","T","p","u","rho"],gasphase) write_csv(csv_g_stream,["z","T","p","u","rho"],gasphase) if chem.surfchem create_header(s_stream,"z","T",md.sm.species) write_csv(csv_s_stream,"z","T",md.sm.species) end #Set up the problem t_span = (0,l) n_species = length(gasphase) if chem.surfchem covg = md.sm.si.ini_covg n_species += length(md.sm.species) end rate = zeros(n_species) all_conc = zeros(n_species) # create the reaction state object for the calculation of surface reaction rates if chem.surfchem #Create the state object surf_conc = similar(covg) rxn_rate = zeros(length(md.sm.reactions)) sr_state = SurfaceRxnState(T, p, mole_fracs, covg, surf_conc , rxn_rate , rate, all_conc) #this step is to get the steady state coverage before starting the plug flow integration t, sr_state = SurfaceReactions.calculate_ss_molar_production_rates!(sr_state,thermo_obj,md,1.0) # params = (state, thermo_obj, md, geometry, os_streams,chem) end # create the reaction state for gasphase if chem.gaschem conc = similar(mole_fracs) source = zeros(length(conc)) g_all = similar(mole_fracs) Kp = zeros(length(gmd.gm.reactions)) rxn_rate = zeros(length(Kp)) gs_state = GasphaseState(T, p, mole_fracs, conc, rxn_rate, source, g_all, Kp) end if chem.userchem && !chem.surfchem && !chem.gaschem source = zeros(length(mole_fracs)) usr_state = UserDefinedState(T,p, mole_fracs, thermo_obj.molwt,gasphase, source) end if chem.surfchem && !chem.gaschem params = (sr_state, thermo_obj, md, geometry, chem) elseif chem.gaschem && !chem.surfchem params = (gs_state, thermo_obj, gmd, geometry, chem) elseif chem.gaschem && chem.surfchem params = (gs_state, sr_state, thermo_obj, md, gmd, geometry, chem) elseif chem.userchem params = (usr_state, thermo_obj, [], geometry, chem) end prob = ODEProblem(residual!,soln,t_span,params) if sens == true return (params, prob, t_span) end cb = FunctionCallingCallback(write_out_put) sol = solve(prob, CVODE_BDF(), reltol=1e-6, abstol=1e-10, save_everystep=false,callback=cb); close(s_stream) close(g_stream) close(csv_g_stream) close(csv_s_stream) return Symbol(sol.retcode) end """ A function for call from other packages, mainly intended for reactor network modeling # Method-3 plug(inlet_comp, T, p, vel, l; chem, thermo_obj, md, geometry) - inlet_comp : Dictionary of species name and mole fractions. In the case of gasphase chemistry the inlet_comp may only contain species that are present at the inlet - T : Temperature in K - p : Pressure in Pa - vel : inlet velocity in m/s - l : length of the reactor in m - chem: Chemistry to be invoked: tuple Chemistry(surfchem, , true, user_defined) - thermo_obj : Thermo Object - md : Mechanism definition(Please refer SurfaceReactions.jl and Ga - geometry : tuple of reactor geometry (dia,cat_geom) - dia: reactor diameter - cat_geom : enhancement factor for the reaction rate due to the catalyst geometry effect """ function plug(inlet_comp, T, p, vel, l; chem, thermo_obj, md, geometry) dia = geometry[Symbol("dia")] Ac = π*dia^2/4.0 As_per_unit_length = π*dia cat_geom = geometry[Symbol("cat_geom")] geom = (Ac,As_per_unit_length,cat_geom) function get_mole_fracs(species, inlet_comp) mole_fracs = zeros(length(species)) for k in eachindex(species) if in(species[k], collect(keys(inlet_comp))) mole_fracs[k] = inlet_comp[species[k]] end end mole_fracs end if chem.surfchem species = collect(keys(inlet_comp)) mole_fracs = get_mole_fracs(species, inlet_comp) covg = md.sm.si.ini_covg #Create the state object surf_conc = similar(covg) rxn_rate = zeros(length(md.sm.reactions)) n_species = length(mole_fracs) + length(covg) rate = zeros(n_species) all_conc = zeros(n_species) sr_state = SurfaceRxnState(T, p, mole_fracs, covg, surf_conc, rxn_rate, rate, all_conc) #this step is to get the steady state coverage before starting the plug flow integration t, sr_state = SurfaceReactions.calculate_ss_molar_production_rates!(sr_state,thermo_obj,md,1.0) params = (sr_state, thermo_obj, md, geom, chem) end if chem.gaschem species = md.gm.species mole_fracs = get_mole_fracs(md.gm.species, inlet_comp) conc = zeros(length(mole_fracs)) source = zeros(length(conc)) g_all = zeros(length(mole_fracs)) Kp = zeros(length(md.gm.reactions)) rxn_rate = zeros(length(Kp)) gs_state = GasphaseState(T, p, mole_fracs, conc, rxn_rate, source, g_all, Kp) params = (gs_state, thermo_obj, md, geom, chem) end ρ = density(mole_fracs,thermo_obj.molwt,T,p) soln = similar(mole_fracs) molefrac_to_massfrac!(soln, mole_fracs, thermo_obj.molwt) push!(soln, vel*ρ) t_span = (0, l) prob = ODEProblem(residual!, soln, t_span, params) sol = solve(prob, CVODE_BDF(), reltol = 1e-6, abstol=1e-10, save_everystep=false) mass_fracs = sol.u[end][1:end-1] mole_fracs = zeros(length(mass_fracs)) massfrac_to_molefrac!(mole_fracs, mass_fracs, thermo_obj.molwt) return sol.t, Dict(species .=> mole_fracs) end #= residual function that defined the governing equations =# function residual!(du,u,p,t) #unpack the parameters state = 1 thermo_obj = 2 md = 3 geom = 4 # state,thermo_obj,md,geom,os_stream = p # Ac,Aspul,cat_geom = geom Ac,Aspul,cat_geom = p[geom] #Convert massfractions to molefractions ng = length(p[state].mole_frac) # massfracs = u[1:ng] massfrac_to_molefrac!(p[state].mole_frac ,u[1:ng], p[thermo_obj].molwt) if p[end].surfchem #Calculate the molar production rates due to surface reactions SurfaceReactions.calculate_ss_molar_production_rates!(p[state],p[thermo_obj],p[md],1.0) p[state].source[1:ng] *= cat_geom*(Aspul/Ac) end if p[end].gaschem && !p[end].surfchem #Calculate the molar production rates due to gasphase reactions GasphaseReactions.calculate_molar_production_rates!(p[state], p[md], p[thermo_obj]) end if p[end].userchem p[end].udf(p[1]) end #species residual du[1:ng] = (p[state].source[1:ng] .* p[thermo_obj].molwt)/u[ng+1] #mass flux du[ng+1] = sum(p[state].source[1:ng] .* p[thermo_obj].molwt) end function write_out_put(u,t,integrator) # state = integrator.p[1] # thermo_obj = integrator.p[2] # g_stream, s_stream = integrator.p[5] g_stream, s_stream, csv_g_stream, csv_s_stream = os_streams d = density(integrator.p[1].mole_frac,integrator.p[2].molwt,integrator.p[1].T,integrator.p[1].p) vel = u[length(integrator.p[1].mole_frac)+1]/d write_to_file(g_stream,t,integrator.p[1].T,integrator.p[1].p,vel,d,integrator.p[1].mole_frac) write_csv(csv_g_stream,t,integrator.p[1].T,integrator.p[1].p,vel,d,integrator.p[1].mole_frac) if integrator.p[end].surfchem write_to_file(s_stream,t,integrator.p[1].T,integrator.p[1].covg) write_csv(csv_s_stream,t,integrator.p[1].T,integrator.p[1].covg) end @printf("%.4e\n", t) end end
PlugFlowReactor
https://github.com/vinodjanardhanan/PlugFlowReactor.jl.git
[ "MIT" ]
0.1.2
168adfc1319d0f98e60edcd3c476a273afedb699
code
2794
using PlugFlowReactor using Test using IdealGas, RxnHelperUtils, SurfaceReactions, ReactionCommons, GasphaseReactions @testset "PlugFlowReactor.jl" begin if Sys.isapple() || Sys.islinux() lib_dir = "lib/" elseif Sys.iswindows() lib_dir = "lib\\" end @testset "Testing surface chemistry" begin input_file = joinpath("plug_surf", "plug.xml") retcode = plug(input_file, lib_dir, surfchem=true) @test retcode == Symbol("Success") end @testset "Testing gas chemistry of h2 + o2" begin input_file = joinpath("plug_h2o2", "plug.xml") retcode = plug(input_file, lib_dir, gaschem=true) @test retcode == Symbol("Success") end @testset "Testing gas chemistry using grimech" begin input_file = joinpath("plug_ch4", "plug.xml") retcode = plug(input_file, lib_dir, gaschem=true) @test retcode == Symbol("Success") end @testset "Testing surface chemistry with interface call " begin inlet_comp = Dict("CH4"=>0.25,"H2O"=>0.0, "H2"=>0.0, "CO"=>0.0, "CO2"=>0.25, "O2"=>0.0, "N2"=>0.5) T = 1073.15 p = 1e5 u = 0.1 l = 0.3 gasphase = collect(keys(inlet_comp)) thermo_obj = IdealGas.create_thermo(gasphase, get_path(lib_dir,"therm.dat")) md = SurfaceReactions.compile_mech(get_path(lib_dir,"ch4ni.xml"),thermo_obj,gasphase) chem = Chemistry(true, false, false, f->()) geometry = (dia=0.005,cat_geom=1000.0) retcodes = plug(inlet_comp, T, p, u, l; chem=chem, thermo_obj=thermo_obj, md=md, geometry=geometry) @test retcodes[1][end] == l end @testset "Testing gasphase chemistry with interface call " begin mech_file = get_path(lib_dir, "h2o2.dat") gmd = compile_gaschemistry(mech_file) gasphase = gmd.gm.species thermo_obj = IdealGas.create_thermo(gasphase, get_path(lib_dir,"therm.dat")) inlet_comp = Dict("O2" => 0.25,"N2" => 0.5, "H2" => 0.25) T = 1073.15 p = 1e5 u = 0.1 l = 0.3 chem = Chemistry(false, true, false, f->()) geometry = (dia=0.005,cat_geom=1.0) retcodes = plug(inlet_comp, T, p, u, l; chem=chem, thermo_obj=thermo_obj, md=gmd, geometry=geometry) @test retcodes[1][end] == l end @testset "Testing user defined chemistry " begin input_file = joinpath("plug_udf", "plug.xml") function udf(state) state.source[1:end] .= 0.0 end retcode = plug(input_file, lib_dir, udf) @test retcode == Symbol("Success") end end
PlugFlowReactor
https://github.com/vinodjanardhanan/PlugFlowReactor.jl.git
[ "MIT" ]
0.1.2
168adfc1319d0f98e60edcd3c476a273afedb699
docs
1039
# PlugFlowReactor [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://vinodjanardhanan.github.io/PlugFlowReactor.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://vinodjanardhanan.github.io/PlugFlowReactor.jl/dev/) [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://vinodjanardhanan.github.io/PlugFlowReactor.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://vinodjanardhanan.github.io/PlugFlowReactor.jl/dev/) [![Build Status](https://github.com/vinodjanardhanan/PlugFlowReactor.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/vinodjanardhanan/PlugFlowReactor.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Build Status](https://travis-ci.com/vinodjanardhanan/PlugFlowReactor.jl.svg?branch=main)](https://travis-ci.com/vinodjanardhanan/PlugFlowReactor.jl) [![Coverage](https://codecov.io/gh/vinodjanardhanan/PlugFlowReactor.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/vinodjanardhanan/PlugFlowReactor.jl)
PlugFlowReactor
https://github.com/vinodjanardhanan/PlugFlowReactor.jl.git
[ "MIT" ]
0.1.2
168adfc1319d0f98e60edcd3c476a273afedb699
docs
9626
```@meta CurrentModule = PlugFlowReactor ``` # PlugFlowReactor Plug is a code for simulating plug flow reactor with detailed surface or gasphase chemistry. Additionally you may use user defined function for the calculation of reaction rates. Documentation for [PlugFlowReactor](https://github.com/vinodjanardhanan/PlugFlowReactor.jl). ## Installation To install the package, use the following commands in the julia REPL ```julia julia> using Pkg julia> Pkg.add("PlugFlowReactor") ``` ## General interfaces ```@index ``` ```@autodocs Modules = [PlugFlowReactor] ``` # Governing equations The governing equations solved are ```math \frac{d (\rho u Y_k)}{dz} = \dot{s_k} M_k \frac{A_{s/L}}{A_c} + \dot{\omega_k}M_k ``` ```math \frac{d (\rho u)}{dz} = \sum_{k=1}^{N_g} \dot{s_k} M_k \frac{A_{s/L}}{A_c} ``` In the above equations, $\rho$ is the density (kg/m$^3$), u is the velocity (m/s), $Y_k$ is the mass fraction of species $k$, z is the axial coordinate (m), $\dot{s_k}$ is the molar production rate of species $k$ due to surface reactions (mol/m$^2$-s), $\dot{\omega}_k$ is the molar production rate of species $k$ due to gasphase reactions (mol/m$^3$-s), $M_k$ is the molecular weight of species $k$, $A_{s/L}$ is the surface area per unit length (m), $A_c$ is the cross sectional area (m$^2$) and $\eta$ is surface area enhancement factor. This factor accounts for the actual surface area available for the surface reactions over the actual geometric surface area of the tubular reactor. # Executing the code ## Surface chemistry For solving a surface chemistry problem: On the Julia REPL ```julia julia>using PlugFlowReactor julia>plug("plug.xml","lib/", surfchem=true) ``` ## Gasphase chemistry For solving a gasphase chemistry problem: On the Julia REPL ```julia julia>using PlugFlowReactor julia>plug("plug.xml", "lib/", gaschem=true) ``` In the above calls, it is assumed that the input file *plug.xml* is present in the working directory and *../lib/* is the path to the *lib* directory relative to the current working directory. The function can be called from any directory and in that case the first argument must point to the *plug.xml* file relative to the current working directory. The output files will be generated in the directory where *plug.xml* is present. In general the function takes three optional keyword arguments *gaschem*, *surfchem*, and *sens*. *gaschem* must be true to simulate gasphase chemistry, *surfchem* must be true for surface chemistry, and *sens* must be true whenever sensitivity analysis is performed. ## User defined chemistry For solving the model with user defined chemistry: On the Julia REPL ```julia julia>using PlugFlowReactor, ReactionCommons julia>plug("plug.xml", "lib/", udf) ``` *udf* is a function having the following signature ``` function udf(state::UserDefinedState) ``` where state is a structure defined as follows ``` struct UserDefinedState T::Float64 p::Float64 molefracs::Array{Float64,1} molwt::Array{Float64,1} species::Array{String,1} source::Array{Float64,1} end ``` The program expects the species source terms in *source* mols/m3-s depending on whether you are solving surface chemistry problem or gasphase chemistry problem. The example call provided in the *runtests.jl* returns zero molar production and consumption rates. Within the code the source terms are multiplied with the molecular weight. The order ing of species source terms must be same as the order in wich the species appears in UserState.species. The structure of the *plug.xml* input file is shown below. ## Input file for surface chemistry problems ``` <?xml version="1.0" encoding="ISO-8859-1"?> <plug> <gasphase>CH4 H2O H2 CO CO2 O2 N2</gasphase> <molefractions>CH4=0.25,CO2=0.25,N2=0.5</molefractions> <T>1073.15</T> <p>1e5</p> <length>0.3</length> <dia>0.005</dia> <u>0.1</u> <Tw>1073.15</Tw> <isothermal>true</isothermal> <cat-geom-factor>1000</cat-geom-factor> <surface_mech>ch4ni.xml</surface_mech> </plug ``` ## Input file for gasphase chemistry problems ``` <?xml version="1.0" encoding="ISO-8859-1"?> <plug> <molefractions>CH4=0.25,CO2=0.25,N2=0.5</molefractions> <T>1073.15</T> <p>1e5</p> <length>0.3</length> <dia>0.005</dia> <u>0.1</u> <Tw>1073.15</Tw> <isothermal>true</isothermal> <gas_mech>ch4ni.xml</gas_mech> </plug ``` The major difference between the input file for surface chemistry problem and gasphase chemistry problem is the *<gasphase>* tag of xml input. In the case of gasphase chemistry problem, the participating species are read from the mechanism input file, which is specified using the *<gas_mech>* tag ## Input file for user defined chemistry problems ``` <?xml version="1.0" encoding="ISO-8859-1"?> <plug> <molefractions>CH4=0.25,CO2=0.25,N2=0.5</molefractions> <T>1073.15</T> <p>1e5</p> <length>0.3</length> <dia>0.005</dia> <u>0.1</u> <Tw>1073.15</Tw> <isothermal>true</isothermal> </plug ``` **Note** Please notice the absence of *<gas_mech>* and *<surface_mech>* tags in the case of user defined chemistry The meaning of different tags is specified below. - <plug> : The root XML tag for Plug - <gasphase> : list of gas-phase species. The species names must be separated by white spaces or tab - <molefractions> : inlet mole fraction of the gas-phase species. Instead of mole fractions, mass fractions may also be specified. In that case, the tag must be <massfractions>. You must ensure that the sum of mass or mole fractions specified is unity. There are no internal checks to ascertain this. - <T>: operating temperature in K - <p>: initial pressure in Pa - <length> : length of the reactor in m - <dia> : diameter of the reactor in m - <u> : inlet velocity of the reacting mixture in m/s - <Tw> : wall temperature in K. This option is provided for performing non-isothermal simulation, which is not supported in the current release - <isothermal> : a boolean which accepts wither true or false. For the current release this must be true - <cat-geom-factor> : surface area enhancement factor (refer $\eta$ in the governing equations) - <surface_mech> : name of the surface reaction mechanism. Must be specified along with the path ## Input file download The xml input file and the *lib* directory containig other required input files may be downloaded from [here](https://github.com/vinodjanardhanan/PlugFlowReactor.jl/tree/main/test). # Output The code generates two output files in the same directory where the input file **`plug.xml`** is present. Two different types of output files are generated for every simulation. a) a **`.dat`** file which contain tab separated values and b) `**.csv`** file which contains the comma separated values. The file **`gas_profile.dat`** contains the mole (or mass) fraction of the gas phase species as a function of time (tab separated). The file **`surf_profile.dat`** contains the surface coverages of adsorbed species as a function of time (tab separated). The file **`gas_profile.csv`** contains the mole (or mass) fraction of the gas phase species as a function of time (comma separated). The file **`surf_profile.csv`** contains the surface coverages of adsorbed species as a function of time (comma separated). In addition to these files, the code also generates terminal output, which shows integration progress. The terminal output is nothing by the integration time. An example terminal output is shown below ``` julia> plug("plug_surf/plug.xml","lib/", surfchem=true) 0.0000e+00 8.8802e-15 8.8811e-11 4.2433e-10 7.5985e-10 ... ... ... 2.1517e-01 2.5184e-01 2.8852e-01 3.0000e-01 :Success ``` A sample output of **`gas_profile.dat`** is shown below ``` z T p u rho CH4 H2O H2 CO CO2 O2 N2 0.0000e+00 1.0732e+03 1.0000e+05 1.0000e-01 3.2524e-01 2.5000e-01 0.0000e+00 0.0000e+00 0.0000e+00 2.5000e-01 0.0000e+00 5.0000e-01 8.8802e-15 1.0732e+03 1.0000e+05 1.0000e-01 3.2524e-01 2.5000e-01 1.5726e-11 5.9064e-12 3.7358e-11 2.5000e-01 1.5402e-23 5.0000e-01 8.8811e-11 1.0732e+03 1.0000e+05 1.0000e-01 3.2524e-01 2.5000e-01 1.5763e-07 5.8187e-08 3.7344e-07 2.5000e-01 1.5149e-19 5.0000e-01 ... ... ... 2.8298e-01 1.0732e+03 1.0000e+05 1.4643e-01 2.2212e-01 1.2200e-02 5.6965e-03 3.1137e-01 3.2276e-01 6.5032e-03 -6.7405e-19 3.4147e-01 3.0000e-01 1.0732e+03 1.0000e+05 1.4643e-01 2.2212e-01 1.2200e-02 5.6965e-03 3.1137e-01 3.2276e-01 6.5032e-03 -4.3287e-13 3.4147e-01 ``` A sample output of **`surf_covg.dat`** is shown below ``` z T (NI) H(NI) O(NI) CH4(NI) H2O(NI) CO2(NI) CO(NI) OH(NI) C(NI) HCO(NI) CH(NI) CH3(NI) CH2(NI) 0.0000e+00 1.0732e+03 8.9517e-01 2.1543e-03 1.0249e-01 1.7333e-09 2.2731e-08 3.4120e-06 1.6186e-04 6.7900e-06 7.3130e-06 1.8236e-17 5.9645e-11 5.3919e-10 3.8717e-10 8.8802e-15 1.0732e+03 8.9517e-01 2.1543e-03 1.0249e-01 1.7333e-09 2.2731e-08 3.4120e-06 1.6186e-04 6.7900e-06 7.3130e-06 1.8236e-17 5.9645e-11 5.3919e-10 3.8717e-10 ... ... ... 2.8298e-01 1.0732e+03 4.1508e-01 1.5854e-01 5.2598e-05 3.9230e-11 6.8172e-06 5.8269e-07 4.2629e-01 5.5308e-07 2.7830e-05 6.5821e-11 1.5517e-11 9.7290e-11 4.8802e-11 3.0000e-01 1.0732e+03 4.1508e-01 1.5854e-01 5.2598e-05 3.9230e-11 6.8172e-06 5.8269e-07 4.2629e-01 5.5308e-07 2.7830e-05 6.5820e-11 1.5517e-11 9.7290e-11 4.8802e-11 ```
PlugFlowReactor
https://github.com/vinodjanardhanan/PlugFlowReactor.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
1242
using CausalELM using Documenter DocMeta.setdocmeta!(CausalELM, :DocTestSetup, :(using CausalELM); recursive=true) makedocs(; modules=[CausalELM], warnonly=true, authors="Darren Colby <[email protected]> and contributors", repo="https://github.com/dscolby/CausalELM.jl/blob/{commit}{path}#{line}", sitename="CausalELM", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://dscolby.github.io/CausalELM.jl", edit_link="main", sidebar_sitename=false, footer="© 2024 Darren Colby", assets=[], ), pages=[ "CausalELM" => "index.md", "Getting Started" => [ "Deciding Which Estimator to Use" => "guide/estimatorselection.md", "Interrupted Time Series Estimation" => "guide/its.md", "G-computation" => "guide/gcomputation.md", "Double Machine Learning" => "guide/doublemachinelearning.md", "Metalearners" => "guide/metalearners.md", ], "API" => "api.md", "Contributing" => "contributing.md", "Release Notes" => "release_notes.md", ], ) deploydocs(; repo="github.com/dscolby/CausalELM.jl", devbranch="main", )
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
1277
""" Macros, functions, and structs for applying Ensembles of extreme learning machines to causal inference tasks where the counterfactual is unavailable or biased and must be predicted. Supports causal inference via interrupted time series designs, parametric G-computation, double machine learning, and S-learning, T-learning, X-learning, R-learning, and doubly robust estimation. For more details on Extreme Learning Machines see: Huang, Guang-Bin, Qin-Yu Zhu, and Chee-Kheong Siew. "Extreme learning machine: theory and applications." Neurocomputing 70, no. 1-3 (2006): 489-501. """ module CausalELM export validate export gelu, gaussian export hard_tanh, elish, fourier export binary_step, σ, tanh, relu export leaky_relu, swish, softmax, softplus export mse, mae, accuracy, precision, recall, F1 export estimate_causal_effect!, summarize, summarise export InterruptedTimeSeries, GComputation, DoubleMachineLearning export SLearner, TLearner, XLearner, RLearner, DoublyRobustLearner include("activation.jl") include("utilities.jl") include("models.jl") include("metrics.jl") include("estimators.jl") include("metalearners.jl") include("inference.jl") include("model_validation.jl") # So that it works with British spelling const summarise = summarize end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
4331
""" binary_step(x) Apply the binary step activation function. # Examples ```jldoctest julia> binary_step(1) 1 julia> binary_step([-1000, 100, 1, 0, -0.001, -3]) 6-element Vector{Int64}: 0 1 1 1 0 0 ``` """ binary_step(x) = ifelse(x < 0, 0, 1) binary_step(x::Array{Float64}) = binary_step.(x) """ σ(x) Apply the sigmoid activation function. # Examples ```jldoctest julia> σ(1) 0.7310585786300049 julia> σ([1.0, 0.0]) 2-element Vector{Float64}: 0.7310585786300049 0.5 ``` """ @inline function σ(x) t = exp(-abs(x)) return ifelse(x ≥ 0, inv(1 + t), t / (1 + t)) end σ(x::Array{Float64}) = σ.(x) """ tanh(x) Apply the hyperbolic tangent activation function. # Examples ```jldoctest julia> CausalELM.tanh([1.0, 0.0]) 2-element Vector{Float64}: 0.7615941559557649 0.0 ``` """ tanh(x::Array{Float64}) = @fastmath tanh.(x) """ relu(x) Apply the ReLU activation function. # Examples ```jldoctest julia> relu(1) 1 julia> relu([1.0, 0.0, -1.0]) 3-element Vector{Float64}: 1.0 0.0 0.0 ``` """ relu(x) = @fastmath ifelse(x < 0, zero(x), x) relu(x::Array{Float64}) = relu.(x) """ leaky_relu(x) Apply the leaky ReLU activation function to a number. # Examples ```jldoctest julia> leaky_relu(1) 1 julia> leaky_relu([-1.0, 0.0, 1.0]) 3-element Vector{Float64}: -0.01 0.0 1.0 ``` """ leaky_relu(x) = @fastmath ifelse(x < 0, 0.01 * x, x) leaky_relu(x::Array{Float64}) = leaky_relu.(x) """ swish(x) Apply the swish activation function to a number. # Examples ```jldoctest julia> swish(1) 0.7310585786300049 julia> swish([1.0, -1.0]) 2-element Vector{Float64}: 0.7310585786300049 -0.2689414213699951 ``` """ swish(x) = x * σ(x) swish(x::Array{Float64}) = swish.(x) """ softmax(x) Apply the softmax activation function to a number. # Examples ```jldoctest julia> softmax(1) 1.0 julia> softmax([1.0, 2.0, 3.0]) 3-element Vector{Float64}: 0.09003057317038045 0.24472847105479764 0.6652409557748219 julia> softmax([1.0 2.0 3.0; 4.0 5.0 6.0]) 2×3 Matrix{Float64}: 0.0900306 0.244728 0.665241 0.0900306 0.244728 0.665241 ``` """ softmax(x) = @fastmath exp(x) / sum(exp(x)) softmax(x::Vector{Float64}) = @fastmath exp.(x .- maximum(x)) / sum(exp.(x .- maximum(x))) softmax(x::Array{Float64}) = mapslices(softmax, x; dims=2) """ softplus(x) Apply the softplus activation function to a number. # Examples ```jldoctest julia> softplus(1) 1.3132616875182228 julia> softplus([1.0, -1.0]) 2-element Vector{Float64}: 1.3132616875182228 0.3132616875182228 ``` """ softplus(x) = @fastmath log1p(exp(-abs(x))) + relu(x) softplus(x::Array{Float64}) = softplus.(x) """ gelu(x) Apply the GeLU activation function to a number. # Examples ```jldoctest julia> gelu(1) 0.8411919906082768 julia> gelu([-1.0, 0.0]) 2-element Vector{Float64}: -0.15880800939172324 0.0 ``` """ gelu(x) = @fastmath (x * (1 + Base.tanh(sqrt(2 / π) * (x + (0.044715 * x^3))))) / 2 gelu(x::Array{Float64}) = gelu.(x) """ gaussian(x) Apply the gaussian activation function to a real number. # Examples ```jldoctest julia> gaussian(1) 0.36787944117144233 julia> gaussian([1.0, -1.0]) 2-element Vector{Float64}: 0.3678794411714423 0.3678794411714423 ``` """ gaussian(x) = @fastmath exp(-abs2(x)) gaussian(x::Array{Float64}) = gaussian.(x) """ hard_tanh(x) Apply the hard_tanh activation function to a number. # Examples ```jldoctest julia> hard_tanh(-2) -1 julia> hard_tanh([-2.0, 0.0, 2.0]) 3-element Vector{Real}: -1 0.0 1 ``` """ @inline function hard_tanh(x) if x < -1 -1 elseif -1 <= x <= 1 x else 1 end end hard_tanh(x::Array{Float64}) = hard_tanh.(x) """ elish(x) Apply the ELiSH activation function to a number. # Examples ```jldoctest julia> elish(1) 0.7310585786300049 julia> elish([-1.0, 1.0]) 2-element Vector{Float64}: -0.17000340156854793 0.7310585786300049 ``` """ elish(x) = ifelse(x >= 0, swish(x), @fastmath ((exp(x) - 1)) * σ(x)) elish(x::Array{Float64}) = elish.(x) """ fourrier(x) Apply the Fourier activation function to a real number. # Examples ```jldoctest julia> fourier(1) 0.8414709848078965 julia> fourier([-1.0, 1.0]) 2-element Vector{Float64}: -0.8414709848078965 0.8414709848078965 ``` """ fourier(x) = @fastmath sin(x) fourier(x::Array{Float64}) = fourier.(x)
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
13679
"""Abstract type for GComputation and DoubleMachineLearning""" abstract type CausalEstimator end """ InterruptedTimeSeries(X₀, Y₀, X₁, Y₁; kwargs...) Initialize an interrupted time series estimator. # Arguments - `X₀::Any`: array or DataFrame of covariates from the pre-treatment period. - `Y₁::Any`: array or DataFrame of outcomes from the pre-treatment period. - `X₁::Any`: array or DataFrame of covariates from the post-treatment period. - `Y₁::Any`: array or DataFrame of outcomes from the post-treatment period. # Keywords - `activation::Function=swish`: activation function to use. - `sample_size::Integer=size(X₀, 1)`: number of bootstrapped samples for the extreme learner. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X₀, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For a simple linear regression-based tutorial on interrupted time series analysis see: Bernal, James Lopez, Steven Cummins, and Antonio Gasparrini. "Interrupted time series regression for the evaluation of public health interventions: a tutorial." International journal of epidemiology 46, no. 1 (2017): 348-355. # Examples ```julia julia> X₀, Y₀, X₁, Y₁ = rand(100, 5), rand(100), rand(10, 5), rand(10) julia> m1 = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁) julia> m2 = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁; regularized=false) julia> x₀_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100)) julia> y₀_df = DataFrame(y=rand(100)) julia> x₁_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100)) julia> y₁_df = DataFrame(y=rand(100)) julia> m3 = InterruptedTimeSeries(x₀_df, y₀_df, x₁_df, y₁_df) ``` """ mutable struct InterruptedTimeSeries X₀::Array{Float64} Y₀::Array{Float64} X₁::Array{Float64} Y₁::Array{Float64} @model_config individual_effect end function InterruptedTimeSeries( X₀, Y₀, X₁, Y₁; activation::Function=swish, sample_size::Integer=size(X₀, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X₀, 2))), num_neurons::Integer=round(Int, log10(size(X₀, 1)) * size(X₀, 2)), autoregression::Bool=true, ) # Convert to arrays X₀, X₁, Y₀, Y₁ = Matrix{Float64}(X₀), Matrix{Float64}(X₁), Y₀[:, 1], Y₁[:, 1] # Add autoregressive term X₀ = ifelse(autoregression == true, reduce(hcat, (X₀, moving_average(Y₀))), X₀) X₁ = ifelse(autoregression == true, reduce(hcat, (X₁, moving_average(Y₁))), X₁) task = var_type(Y₀) isa Binary ? "classification" : "regression" return InterruptedTimeSeries( X₀, float(Y₀), X₁, float(Y₁), "difference", true, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(Y₁, 1)), ) end """ GComputation(X, T, Y; kwargs...) Initialize a G-Computation estimator. # Arguments - `X::Any`: array or DataFrame of covariates. - `T::Any`: vector or DataFrame of treatment statuses. - `Y::Any`: array or DataFrame of outcomes. # Keywords - `quantity_of_interest::String`: ATE for average treatment effect or ATT for average treatment effect on the treated. - `activation::Function=swish`: activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for the extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For a good overview of G-Computation see: Chatton, Arthur, Florent Le Borgne, Clémence Leyrat, Florence Gillaizeau, Chloé Rousseau, Laetitia Barbin, David Laplaud, Maxime Léger, Bruno Giraudeau, and Yohann Foucher. "G-computation, propensity score-based methods, and targeted maximum likelihood estimator for causal inference with different covariates sets: a comparative simulation study." Scientific reports 10, no. 1 (2020): 9219. # Examples ```julia julia> X, T, Y = rand(100, 5), rand(100), [rand()<0.4 for i in 1:100] julia> m1 = GComputation(X, T, Y) julia> m2 = GComputation(X, T, Y; task="regression") julia> m3 = GComputation(X, T, Y; task="regression", quantity_of_interest="ATE) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m5 = GComputation(x_df, t_df, y_df) ``` """ mutable struct GComputation <: CausalEstimator @standard_input_data @model_config average_effect ensemble::ELMEnsemble function GComputation( X, T, Y; quantity_of_interest::String="ATE", activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), temporal::Bool=true, ) if quantity_of_interest ∉ ("ATE", "ITT", "ATT") throw(ArgumentError("quantity_of_interest must be ATE, ITT, or ATT")) end # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] task = var_type(Y) isa Binary ? "classification" : "regression" return new( X, float(T), float(Y), quantity_of_interest, temporal, task, activation, sample_size, num_machines, num_feats, num_neurons, NaN, ) end end """ DoubleMachineLearning(X, T, Y; kwargs...) Initialize a double machine learning estimator with cross fitting. # Arguments - `X::Any`: array or DataFrame of covariates of interest. - `T::Any`: vector or DataFrame of treatment statuses. - `Y::Any`: array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for teh extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75, * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. - `folds::Integer`: number of folds to use for cross fitting. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For more information see: Chernozhukov, Victor, Denis Chetverikov, Mert Demirer, Esther Duflo, Christian Hansen, Whitney Newey, and James Robins. "Double/debiased machine learning for treatment and structural parameters." (2016): C1-C68. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = DoubleMachineLearning(X, T, Y) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m2 = DoubleMachineLearning(x_df, t_df, y_df) ``` """ mutable struct DoubleMachineLearning <: CausalEstimator @standard_input_data @model_config average_effect folds::Integer end function DoubleMachineLearning( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * num_feats), folds::Integer=5, ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] # Shuffle data with random indices indices = shuffle(1:length(Y)) X, T, Y = X[indices, :], T[indices], Y[indices] task = var_type(Y) isa Binary ? "classification" : "regression" return DoubleMachineLearning( X, float(T), float(Y), "ATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, NaN, folds, ) end """ estimate_causal_effect!(its) Estimate the effect of an event relative to a predicted counterfactual. # Examples ```julia julia> X₀, Y₀, X₁, Y₁ = rand(100, 5), rand(100), rand(10, 5), rand(10) julia> m1 = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁) julia> estimate_causal_effect!(m1) ``` """ function estimate_causal_effect!(its::InterruptedTimeSeries) learner = ELMEnsemble( its.X₀, its.Y₀, its.sample_size, its.num_machines, its.num_feats, its.num_neurons, its.activation ) fit!(learner) its.causal_effect = predict(learner, its.X₁) - its.Y₁ return its.causal_effect end """ estimate_causal_effect!(g) Estimate a causal effect of interest using G-Computation. # Notes If treatents are administered at multiple time periods, the effect will be estimated as the average difference between the outcome of being treated in all periods and being treated in no periods. For example, given that ividuals 1, 2, ..., i ∈ I recieved either a treatment or a placebo in p different periods, the model would estimate the average treatment effect as E[Yᵢ|T₁=1, T₂=1, ... Tₚ=1, Xₚ] - E[Yᵢ|T₁=0, T₂=0, ... Tₚ=0, Xₚ]. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = GComputation(X, T, Y) julia> estimate_causal_effect!(m1) ``` """ function estimate_causal_effect!(g::GComputation) g.causal_effect = mean(g_formula!(g)) return g.causal_effect end """ g_formula!(g) Compute the G-formula for G-computation and S-learning. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = GComputation(X, T, Y) julia> g_formula!(m1) julia> m2 = SLearner(X, T, Y) julia> g_formula!(m2) ``` """ function g_formula!(g) # Keeping this separate enables it to be reused for S-Learning covariates, y = hcat(g.X, g.T), g.Y if g.quantity_of_interest ∈ ("ITT", "ATE", "CATE") Xₜ = hcat(covariates[:, 1:(end - 1)], ones(size(covariates, 1))) Xᵤ = hcat(covariates[:, 1:(end - 1)], zeros(size(covariates, 1))) else Xₜ = hcat(covariates[g.T .== 1, 1:(end - 1)], ones(size(g.T[g.T .== 1], 1))) Xᵤ = hcat(covariates[g.T .== 1, 1:(end - 1)], zeros(size(g.T[g.T .== 1], 1))) end g.ensemble = ELMEnsemble( covariates, y, g.sample_size, g.num_machines, g.num_feats, g.num_neurons, g.activation ) fit!(g.ensemble) yₜ, yᵤ = predict(g.ensemble, Xₜ), predict(g.ensemble, Xᵤ) return vec(yₜ) - vec(yᵤ) end """ estimate_causal_effect!(DML) Estimate a causal effect of interest using double machine learning. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = DoubleMachineLearning(X, T, Y) julia> estimate_causal_effect!(m1) julia> W = rand(100, 6) julia> m2 = DoubleMachineLearning(X, T, Y, W=W) julia> estimate_causal_effect!(m2) ``` """ function estimate_causal_effect!(DML::DoubleMachineLearning) X, T, Y = generate_folds(DML.X, DML.T, DML.Y, DML.folds) DML.causal_effect = 0 # Cross fitting by training on the main folds and predicting residuals on the auxillary for fld in 1:(DML.folds) X_train, X_test = reduce(vcat, X[1:end .!== fld]), X[fld] Y_train, Y_test = reduce(vcat, Y[1:end .!== fld]), Y[fld] T_train, T_test = reduce(vcat, T[1:end .!== fld]), T[fld] Ỹ, T̃ = predict_residuals(DML, X_train, X_test, Y_train, Y_test, T_train, T_test) DML.causal_effect += T̃\Ỹ end DML.causal_effect /= DML.folds return DML.causal_effect end """ predict_residuals(D, x_train, x_test, y_train, y_test, t_train, t_test) Predict treatment and outcome residuals for double machine learning or R-learning. # Notes This method should not be called directly. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> x_train, x_test = X[1:80, :], X[81:end, :] julia> y_train, y_test = Y[1:80], Y[81:end] julia> t_train, t_test = T[1:80], T[81:100] julia> m1 = DoubleMachineLearning(X, T, Y) julia> predict_residuals(m1, x_train, x_test, y_train, y_test, t_train, t_test) ``` """ function predict_residuals( D, xₜᵣ::Array{Float64}, xₜₑ::Array{Float64}, yₜᵣ::Vector{Float64}, yₜₑ::Vector{Float64}, tₜᵣ::Vector{Float64}, tₜₑ::Vector{Float64}, ) y = ELMEnsemble( xₜᵣ, yₜᵣ, D.sample_size, D.num_machines, D.num_feats, D.num_neurons, D.activation ) t = ELMEnsemble( xₜᵣ, tₜᵣ, D.sample_size, D.num_machines, D.num_feats, D.num_neurons, D.activation ) fit!(y) fit!(t) yₚᵣ, tₚᵣ = predict(y, xₜₑ), predict(t, xₜₑ) return yₜₑ - yₚᵣ, tₜₑ - tₚᵣ end """ moving_average(x) Calculates a cumulative moving average. # Examples ```julia julia> moving_average([1, 2, 3]) ``` """ function moving_average(x) result = similar(x) for i in 1:length(x) result[i] = mean(x[1:i]) end return result end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
10211
using Random: shuffle """ summarize(mod, kwargs...) Get a summary from a CausalEstimator or Metalearner. # Arguments - `mod::Union{CausalEstimator, Metalearner}`: a model to summarize. # Keywords - `n::Int=100`: the number of iterations to generate the numll distribution for randomization inference. - `inference::Bool`=false: wheteher calculate p-values and standard errors. # Notes p-values and standard errors are estimated using approximate randomization inference. If set to true, this procedure takes a VERY long time due to repeated matrix inversions. # References For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = GComputation(X, T, Y) julia> estimate_causal_effect!(m1) julia> summarize(m1) julia> m2 = RLearner(X, T, Y) julia> estimate_causal_effect(m2) julia> summarize(m2) julia> m3 = SLearner(X, T, Y) julia> estimate_causal_effect!(m3) julia> summarise(m3) # British spelling works too! ``` """ function summarize(mod; n=1000, inference=false) if all(isnan, mod.causal_effect) throw(ErrorException("call estimate_causal_effect! before calling summarize")) end summary_dict = Dict() nicenames = [ "Task", "Quantity of Interest", "Activation Function", "Sample Size", "Number of Machines", "Number of Features", "Number of Neurons", "Time Series/Panel Data", "Causal Effect", "Standard Error", "p-value", ] if inference p, stderr = quantities_of_interest(mod, n) else p, stderr = NaN, NaN end values = [ mod.task, mod.quantity_of_interest, mod.activation, mod.sample_size, mod.num_machines, mod.num_feats, mod.num_neurons, mod.temporal, mod.causal_effect, stderr, p, ] for (nicename, value) in zip(nicenames, values) summary_dict[nicename] = value end return summary_dict end """ summarize(its, kwargs...) Get a summary from an interrupted time series estimator. # Arguments - `its::InterruptedTimeSeries`: interrupted time series estimator # Keywords - `n::Int=100`: number of iterations to generate the numll distribution for randomization inference. - `mean_effect::Bool=true`: whether to estimate the mean or cumulative effect for an interrupted time series estimator. - `inference::Bool`=false: wheteher calculate p-values and standard errors. # Notes p-values and standard errors are estimated using approximate randomization inference. If set to true, this procedure takes a VERY long time due to repeated matrix inversions. # Examples ```julia julia> X₀, Y₀, X₁, Y₁ = rand(100, 5), rand(100), rand(10, 5), rand(10) julia> m4 = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁) julia> estimate_causal_effect!(m4) julia> summarize(m4) ``` """ function summarize(its::InterruptedTimeSeries; n=1000, mean_effect=true, inference=false) if all(isnan, its.causal_effect) throw(ErrorException("call estimate_causal_effect! before calling summarize")) end effect = ifelse(mean_effect, mean(its.causal_effect), sum(its.causal_effect)) qoi = mean_effect ? "Average Difference" : "Cumulative Difference" if inference p, stderr = quantities_of_interest(its, n, mean_effect) else p, stderr = NaN, NaN end summary_dict = Dict() nicenames = [ "Task", "Quantity of Interest", "Activation Function", "Sample Size", "Number of Machines", "Number of Features", "Number of Neurons", "Time Series/Panel Data", "Causal Effect", "Standard Error", "p-value", ] values = [ its.task, qoi, its.activation, its.sample_size, its.num_machines, its.num_feats, its.num_neurons, its.temporal, effect, stderr, p, ] for (nicename, value) in zip(nicenames, values) summary_dict[nicename] = value end return summary_dict end """ generate_null_distribution(mod, n) Generate a null distribution for the treatment effect of G-computation, double machine learning, or metalearning. # Arguments - `mod::Any`: model to summarize. - `n::Int=100`: number of iterations to generate the null distribution for randomization inference. # Notes This method estimates the same model that is provided using random permutations of the treatment assignment to generate a vector of estimated effects under different treatment regimes. When mod is a metalearner the null statistic is the difference is the ATE. Note that lowering the number of iterations increases the probability of failing to reject the null hypothesis. # Examples ```julia julia> x, t, y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(1:100, 100, 1) julia> g_computer = GComputation(x, t, y) julia> estimate_causal_effect!(g_computer) julia> generate_null_distribution(g_computer, 500) ``` """ function generate_null_distribution(mod, n) nobs, mods = size(mod.T, 1), [deepcopy(mod) for i ∈ 1:n] results = Vector{Float64}(undef, n) # Generate random treatment assignments and estimate the causal effects Threads.@threads for i ∈ 1:n # Sample from a continuous distribution if the treatment is continuous if var_type(mod.T) isa Continuous mods[i].T = (maximum(mod.T) - minimum(mod.T)) .* rand(nobs) .+ minimum(mod.T) else mods[i].T = float(rand(unique(mod.T), nobs)) end estimate_causal_effect!(mods[i]) results[i] = if mod isa Metalearner mean(mods[i].causal_effect) else mods[i].causal_effect end end return results end """ generate_null_distribution(its, n, mean_effect) # Arguments - `its::InterruptedTimeSeries`: interrupted time series estimator - `n::Int=100`: number of iterations to generate the numll distribution for randomization inference. - `mean_effect::Bool=true`: whether to estimate the mean or cumulative effect for an interrupted time series estimator. # Examples ```julia julia> x₀, y₀, x₁, y₁ = rand(1:100, 100, 5), rand(100), rand(10, 5), rand(10) julia> its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) julia> estimate_causal_effect!(its) julia> generate_null_distribution(its, 10) ``` """ function generate_null_distribution(its::InterruptedTimeSeries, n, mean_effect) mods = [deepcopy(its) for i ∈ 1:n] split_idx = size(its.Y₀, 1) results = Vector{Float64}(undef, n) data = reduce(hcat, (reduce(vcat, (its.X₀, its.X₁)), reduce(vcat, (its.Y₀, its.Y₁)))) # Generate random treatment assignments and estimate the causal effects Threads.@threads for iter in 1:n local permuted_data = data[shuffle(1:end), :] local permuted_x₀ = permuted_data[1:split_idx, 1:(end - 1)] local permuted_x₁ = permuted_data[(split_idx + 1):end, 1:(end - 1)] local permuted_y₀ = permuted_data[1:split_idx, end] local permuted_y₁ = permuted_data[(split_idx + 1):end, end] # Reestimate the model with the intervention now at the nth interval mods[iter].X₀, mods[iter].Y₀ = permuted_x₀, permuted_y₀ mods[iter].X₁, mods[iter].Y₁ = permuted_x₁, permuted_y₁ estimate_causal_effect!(mods[iter]) results[iter] = if mean_effect mean(mods[iter].causal_effect) else sum(mods[iter].causal_effect) end end return results end """ quantities_of_interest(mod, n) Generate a p-value and standard error through randomization inference This method generates a null distribution of treatment effects by reestimating treatment effects from permutations of the treatment vector and estimates a p-value and standard from the generated distribution. Note that lowering the number of iterations increases the probability of failing to reject the null hypothesis. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> x, t, y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(1:100, 100, 1) julia> g_computer = GComputation(x, t, y) julia> estimate_causal_effect!(g_computer) julia> quantities_of_interest(g_computer, 1000) ``` """ function quantities_of_interest(mod, n) null_dist = generate_null_distribution(mod, n) avg_effect = mod isa Metalearner ? mean(mod.causal_effect) : mod.causal_effect extremes = length(null_dist[abs(avg_effect) .< abs.(null_dist)]) pvalue = extremes / n stderr = sqrt(sum([(avg_effect .- x)^2 for x in null_dist]) / (n - 1)) / sqrt(n) return pvalue, stderr end """ quantities_of_interest(mod, n) Generate a p-value and standard error through randomization inference This method generates a null distribution of treatment effects by reestimating treatment effects from permutations of the treatment vector and estimates a p-value and standard from the generated distribution. Randomization for event studies is done by creating time splits at even intervals and reestimating the causal effect. Note that lowering the number of iterations increases the probability of failing to reject the null hypothesis. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> x₀, y₀, x₁, y₁ = rand(1:100, 100, 5), rand(100), rand(10, 5), rand(10) julia> its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) julia> estimate_causal_effect!(its) julia> quantities_of_interest(its, 10) ``` """ function quantities_of_interest(mod::InterruptedTimeSeries, n, mean_effect) local null_dist = generate_null_distribution(mod, n, mean_effect) local metric = ifelse(mean_effect, mean, sum) local effect = metric(mod.causal_effect) extremes = length(null_dist[effect .< abs.(null_dist)]) pvalue = extremes / n stderr = (sum([(effect .- x)^2 for x in null_dist]) / (n - 1)) / sqrt(n) return pvalue, stderr end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
20859
"""Abstract type for metalearners""" abstract type Metalearner end """ SLearner(X, T, Y; kwargs...) Initialize a S-Learner. # Arguments - `X::Any`: an array or DataFrame of covariates. - `T::Any`: an vector or DataFrame of treatment statuses. - `Y::Any`: an array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: the activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for eth extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For an overview of S-Learners and other metalearners see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = SLearner(X, T, Y) julia> m2 = SLearner(X, T, Y; task="regression") julia> m3 = SLearner(X, T, Y; task="regression", regularized=true) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m4 = SLearner(x_df, t_df, y_df) ``` """ mutable struct SLearner <: Metalearner @standard_input_data @model_config individual_effect ensemble::ELMEnsemble function SLearner( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] task = var_type(Y) isa Binary ? "classification" : "regression" return new( X, Float64.(T), Float64.(Y), "CATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(T, 1)), ) end end """ TLearner(X, T, Y; kwargs...) Initialize a T-Learner. # Arguments - `X::Any`: an array or DataFrame of covariates. - `T::Any`: an vector or DataFrame of treatment statuses. - `Y::Any`: an array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: the activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for eth extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For an overview of T-Learners and other metalearners see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = TLearner(X, T, Y) julia> m2 = TLearner(X, T, Y; regularized=false) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m3 = TLearner(x_df, t_df, y_df) ``` """ mutable struct TLearner <: Metalearner @standard_input_data @model_config individual_effect μ₀::ELMEnsemble μ₁::ELMEnsemble function TLearner( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] task = var_type(Y) isa Binary ? "classification" : "regression" return new( X, Float64.(T), Float64.(Y), "CATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(T, 1)), ) end end """ XLearner(X, T, Y; kwargs...) Initialize an X-Learner. # Arguments - `X::Any`: an array or DataFrame of covariates. - `T::Any`: an vector or DataFrame of treatment statuses. - `Y::Any`: an array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: the activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for eth extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For an overview of X-Learners and other metalearners see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = XLearner(X, T, Y) julia> m2 = XLearner(X, T, Y; regularized=false) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m3 = XLearner(x_df, t_df, y_df) ``` """ mutable struct XLearner <: Metalearner @standard_input_data @model_config individual_effect μ₀::ELMEnsemble μ₁::ELMEnsemble ps::Array{Float64} function XLearner( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] task = var_type(Y) isa Binary ? "classification" : "regression" return new( X, Float64.(T), Float64.(Y), "CATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(T, 1)), ) end end """ RLearner(X, T, Y; kwargs...) Initialize an R-Learner. # Arguments - `X::Any`: an array or DataFrame of covariates of interest. - `T::Any`: an vector or DataFrame of treatment statuses. - `Y::Any`: an array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: the activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for eth extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. ## References For an explanation of R-Learner estimation see: Nie, Xinkun, and Stefan Wager. "Quasi-oracle estimation of heterogeneous treatment effects." Biometrika 108, no. 2 (2021): 299-319. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = RLearner(X, T, Y) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m2 = RLearner(x_df, t_df, y_df) ``` """ mutable struct RLearner <: Metalearner @standard_input_data @model_config individual_effect folds::Integer end function RLearner( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), folds::Integer=5, ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] # Shuffle data with random indices indices = shuffle(1:length(Y)) X, T, Y = X[indices, :], T[indices], Y[indices] task = var_type(Y) isa Binary ? "classification" : "regression" return RLearner( X, Float64.(T), Float64.(Y), "CATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(T, 1)), folds, ) end """ DoublyRobustLearner(X, T, Y; kwargs...) Initialize a doubly robust CATE estimator. # Arguments - `X::Any`: an array or DataFrame of covariates of interest. - `T::Any`: an vector or DataFrame of treatment statuses. - `Y::Any`: an array or DataFrame of outcomes. # Keywords - `activation::Function=swish`: the activation function to use. - `sample_size::Integer=size(X, 1)`: number of bootstrapped samples for eth extreme learners. - `num_machines::Integer=50`: number of extreme learning machines for the ensemble. - `num_feats::Integer=Int(round(0.75 * size(X, 2)))`: number of features to bootstrap for each learner in the ensemble. - `num_neurons::Integer`: number of neurons to use in the extreme learning machines. # Notes To reduce the computational complexity you can reduce sample_size, num_machines, or num_neurons. # References For an explanation of doubly robust cate estimation see: Kennedy, Edward H. "Towards optimal doubly robust estimation of heterogeneous causal effects." Electronic Journal of Statistics 17, no. 2 (2023): 3008-3049. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = DoublyRobustLearner(X, T, Y) julia> x_df = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) julia> t_df, y_df = DataFrame(t=rand(0:1, 100)), DataFrame(y=rand(100)) julia> m2 = DoublyRobustLearner(x_df, t_df, y_df) julia> w = rand(100, 6) julia> m3 = DoublyRobustLearner(X, T, Y, W=w) ``` """ mutable struct DoublyRobustLearner <: Metalearner @standard_input_data @model_config individual_effect folds::Integer end function DoublyRobustLearner( X, T, Y; activation::Function=swish, sample_size::Integer=size(X, 1), num_machines::Integer=50, num_feats::Integer=Int(round(0.75 * size(X, 2))), num_neurons::Integer=round(Int, log10(size(X, 1)) * size(X, 2)), ) # Convert to arrays X, T, Y = Matrix{Float64}(X), T[:, 1], Y[:, 1] # Shuffle data with random indices indices = shuffle(1:length(Y)) X, T, Y = X[indices, :], T[indices], Y[indices] task = var_type(Y) isa Binary ? "classification" : "regression" return DoublyRobustLearner( X, Float64.(T), Float64.(Y), "CATE", false, task, activation, sample_size, num_machines, num_feats, num_neurons, fill(NaN, size(T, 1)), 2, ) end """ estimate_causal_effect!(s) Estimate the CATE using an S-learner. # References For an overview of S-learning see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m4 = SLearner(X, T, Y) julia> estimate_causal_effect!(m4) ``` """ function estimate_causal_effect!(s::SLearner) s.causal_effect = g_formula!(s) return s.causal_effect end """ estimate_causal_effect!(t) Estimate the CATE using an T-learner. # References For an overview of T-learning see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m5 = TLearner(X, T, Y) julia> estimate_causal_effect!(m5) ``` """ function estimate_causal_effect!(t::TLearner) x₀, x₁, y₀, y₁ = t.X[t.T .== 0, :], t.X[t.T .== 1, :], t.Y[t.T .== 0], t.Y[t.T .== 1] t.μ₀ = ELMEnsemble( x₀, y₀, t.sample_size, t.num_machines, t.num_feats, t.num_neurons, t.activation ) t.μ₁ = ELMEnsemble( x₁, y₁, t.sample_size, t.num_machines, t.num_feats, t.num_neurons, t.activation ) fit!(t.μ₀) fit!(t.μ₁) predictionsₜ, predictionsᵪ = predict(t.μ₁, t.X), predict(t.μ₀, t.X) t.causal_effect = @fastmath vec(predictionsₜ - predictionsᵪ) return t.causal_effect end """ estimate_causal_effect!(x) Estimate the CATE using an X-learner. # References For an overview of X-learning see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = XLearner(X, T, Y) julia> estimate_causal_effect!(m1) ``` """ function estimate_causal_effect!(x::XLearner) stage1!(x) μχ₀, μχ₁ = stage2!(x) x.causal_effect = @fastmath vec(( (x.ps .* predict(μχ₀, x.X)) .+ ((1 .- x.ps) .* predict(μχ₁, x.X)) )) return x.causal_effect end """ estimate_causal_effect!(R) Estimate the CATE using an R-learner. # References For an overview of R-learning see: Nie, Xinkun, and Stefan Wager. "Quasi-oracle estimation of heterogeneous treatment effects." Biometrika 108, no. 2 (2021): 299-319. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = RLearner(X, T, Y) julia> estimate_causal_effect!(m1) ``` """ function estimate_causal_effect!(R::RLearner) X, T̃, Ỹ = generate_folds(R.X, R.T, R.Y, R.folds) R.X, R.T, R.Y = reduce(vcat, X), reduce(vcat, T̃), reduce(vcat, Ỹ) # Get residuals from out-of-fold predictions for f in 1:(R.folds) X_train, X_test = reduce(vcat, X[1:end .!== f]), X[f] Y_train, Y_test = reduce(vcat, Ỹ[1:end .!== f]), Ỹ[f] T_train, T_test = reduce(vcat, T̃[1:end .!== f]), T̃[f] Ỹ[f], T̃[f] = predict_residuals(R, X_train, X_test, Y_train, Y_test, T_train, T_test) end # Using target transformation and the weight trick to minimize the causal loss T̃², target = reduce(vcat, T̃).^2, reduce(vcat, Ỹ) ./ reduce(vcat, T̃) Xʷ, Yʷ = R.X .* T̃², target .* T̃² # Fit a weighted residual-on-residual model final_model = ELMEnsemble( Xʷ, Yʷ, R.sample_size, R.num_machines, R.num_feats, R.num_neurons, R.activation ) fit!(final_model) R.causal_effect = predict(final_model, R.X) return R.causal_effect end """ estimate_causal_effect!(DRE) Estimate the CATE using a doubly robust learner. # References For details on how this method estimates the CATE see: Kennedy, Edward H. "Towards optimal doubly robust estimation of heterogeneous causal effects." Electronic Journal of Statistics 17, no. 2 (2023): 3008-3049. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = DoublyRobustLearner(X, T, Y) julia> estimate_causal_effect!(m1) ``` """ function estimate_causal_effect!(DRE::DoublyRobustLearner) X, T, Y = generate_folds(DRE.X, DRE.T, DRE.Y, DRE.folds) causal_effect = zeros(size(DRE.T, 1)) # Rotating folds for cross fitting for i in 1:2 causal_effect .+= doubly_robust_formula!(DRE, X, T, Y) X, T, Y = [X[2], X[1]], [T[2], T[1]], [Y[2], Y[1]] end causal_effect ./= 2 DRE.causal_effect = causal_effect return DRE.causal_effect end """ doubly_robust_formula!(DRE, X, T, Y) Estimate the CATE for a single cross fitting iteration via doubly robust estimation. # Notes This method should not be called directly. # Arguments - `DRE::DoublyRobustLearner`: the DoubleMachineLearning struct to estimate the effect for. - `X`: a vector of three covariate folds. - `T`: a vector of three treatment folds. - `Y`: a vector of three outcome folds. # Examples ```julia julia> X, T, Y, W = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100), rand(6, 100) julia> m1 = DoublyRobustLearner(X, T, Y) julia> X, T, W, Y = make_folds(m1) julia> Z = m1.W == m1.X ? X : [reduce(hcat, (z)) for z in zip(X, W)] julia> g_formula!(m1, X, T, Y, Z) ``` """ function doubly_robust_formula!(DRE::DoublyRobustLearner, X, T, Y) # Propensity scores π_e = ELMEnsemble( X[1], T[1], DRE.sample_size, DRE.num_machines, DRE.num_feats, DRE.num_neurons, DRE.activation ) # Outcome models μ₀ = ELMEnsemble( X[1][T[1] .== 0, :], Y[1][T[1] .== 0], DRE.sample_size, DRE.num_machines, DRE.num_feats, DRE.num_neurons, DRE.activation ) μ₁ = ELMEnsemble( X[1][T[1] .== 1, :], Y[1][T[1] .== 1], DRE.sample_size, DRE.num_machines, DRE.num_feats, DRE.num_neurons, DRE.activation ) fit!.((π_e, μ₀, μ₁)) π̂ , μ₀̂, μ₁̂ = predict(π_e, X[2]), predict(μ₀, X[2]), predict(μ₁, X[2]) # Pseudo outcomes ϕ̂ = ((T[2] .- π̂) ./ (π̂ .* (1 .- π̂))) .* (Y[2] .- T[2] .* μ₁̂ .- (1 .- T[2]) .* μ₀̂) .+ μ₁̂ .- μ₀̂ # Final model τ_est = ELMEnsemble( X[2], ϕ̂, DRE.sample_size, DRE.num_machines, DRE.num_feats, DRE.num_neurons, DRE.activation ) fit!(τ_est) return predict(τ_est, DRE.X) end """ stage1!(x) Estimate the first stage models for an X-learner. # Notes This method should not be called by the user. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = XLearner(X, T, Y) julia> stage1!(m1) ``` """ function stage1!(x::XLearner) g = ELMEnsemble( x.X, x.T, x.sample_size, x.num_machines, x.num_feats, x.num_neurons, x.activation ) x.μ₀ = ELMEnsemble( x.X[x.T .== 0, :], x.Y[x.T .== 0], x.sample_size, x.num_machines, x.num_feats, x.num_neurons, x.activation ) x.μ₁ = ELMEnsemble( x.X[x.T .== 1, :], x.Y[x.T .== 1], x.sample_size, x.num_machines, x.num_feats, x.num_neurons, x.activation ) # Get propensity scores fit!(g) x.ps = predict(g, x.X) # Fit first stage outcome models fit!(x.μ₀) return fit!(x.μ₁) end """ stage2!(x) Estimate the second stage models for an X-learner. # Notes This method should not be called by the user. # Examples ```julia julia> X, T, Y = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100) julia> m1 = XLearner(X, T, Y) julia> stage1!(m1) julia> stage2!(m1) ``` """ function stage2!(x::XLearner) m₁, m₀ = predict(x.μ₁, x.X .- x.Y), predict(x.μ₀, x.X) d = ifelse(x.T === 0, m₁, x.Y .- m₀) μχ₀ = ELMEnsemble( x.X[x.T .== 0, :], d[x.T .== 0], x.sample_size, x.num_machines, x.num_feats, x.num_neurons, x.activation ) μχ₁ = ELMEnsemble( x.X[x.T .== 1, :], d[x.T .== 1], x.sample_size, x.num_machines, x.num_feats, x.num_neurons, x.activation ) fit!(μχ₀) fit!(μχ₁) return μχ₀, μχ₁ end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
3639
using LinearAlgebra: diag, replace! """ mse(y, ŷ) Calculate the mean squared error See also [`mae`](@ref). Examples ```jldoctest julia> mse([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]) 4.0 ``` """ function mse(y, ŷ) if length(y) !== length(ŷ) throw(DimensionMismatch("y and ̂y must be the same length")) end return @fastmath sum((y - ŷ) .^ 2) / length(y) end """ mae(y, ŷ) Calculate the mean absolute error See also [`mse`](@ref). # Examples ```jldoctest julia> mae([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]) 2.0 ``` """ function mae(y, ŷ) if length(y) !== length(ŷ) throw(DimensionMismatch("y and ̂y must be the same length")) end return @fastmath sum(abs.(y .- ŷ)) / length(y) end """ accuracy(y, ŷ) Calculate the accuracy for a classification task # Examples ```julia julia> accuracy([1, 1, 1, 1], [0, 1, 1, 0]) 0.5 ``` """ function accuracy(y, ŷ) if length(y) !== length(ŷ) throw(DimensionMismatch("y and ̂y must be the same length")) end # Converting from one hot encoding to the original representation if y is multiclass if !isa(y, Vector) y, ŷ = vec(mapslices(argmax, y; dims=2)), vec(mapslices(argmax, ŷ; dims=2)) end @fastmath differences = y .- ŷ return @fastmath length(differences[differences .== 0]) / length(ŷ) end """ precision(y, ŷ) Calculate the precision for a classification task See also [`recall`](@ref). # Examples ```jldoctest julia> CausalELM.precision([0, 1, 0, 0], [0, 1, 1, 0]) 1.0 ``` """ function precision(y::Array{Int64}, ŷ::Array{Int64}) confmat = confusion_matrix(y, ŷ) if size(confmat) == (2, 2) confmat[1, 1] == 0 && 0.0 confmat[1, 2] == 0 && 1.0 return @fastmath confmat[1, 1] / sum(confmat[1, :]) else intermediate = @fastmath diag(confmat) ./ vec(sum(confmat; dims=2)) replace!(intermediate, NaN => 0) return mean(intermediate) end end """ recall(y, ŷ) Calculate the recall for a classification task See also [`CausalELM.precision`](@ref). # Examples ```jldoctest julia> recall([1, 2, 1, 3, 0], [2, 2, 2, 3, 1]) 0.5 ``` """ function recall(y, ŷ) confmat = confusion_matrix(y, ŷ) if size(confmat) == (2, 2) confmat[1, 1] == 0 && 0.0 confmat[2, 1] == 0 && 1.0 return @fastmath confmat[1, 1] / sum(confmat[:, 1]) else intermediate = @fastmath diag(confmat) ./ vec(sum(confmat; dims=1)) replace!(intermediate, NaN => 0) return mean(intermediate) end end """ F1(y, ŷ) Calculate the F1 score for a classification task # Examples ```jldoctest julia> F1([1, 2, 1, 3, 0], [2, 2, 2, 3, 1]) 0.4 ``` """ function F1(y, ŷ) prec, rec = precision(y, ŷ), recall(y, ŷ) return @fastmath 2(prec * rec) / (prec + rec) end """ confusion_matrix(y, ŷ) Generate a confusion matrix # Examples ```jldoctest julia> CausalELM.confusion_matrix([1, 1, 1, 1, 0], [1, 1, 1, 1, 0]) 2×2 Matrix{Int64}: 1 0 0 4 ``` """ function confusion_matrix(y, ŷ) # Converting from one hot encoding to the original representation if y is multiclass if !isa(y, Vector) y, ŷ = vec(mapslices(argmax, y; dims=2)), vec(mapslices(argmax, ŷ; dims=2)) end # Recode since Julia is a 1-index language flor = minimum(vcat(y, ŷ)) if flor < 1 @fastmath y .+= (1 - flor) @fastmath ŷ .+= (1 - flor) end n = maximum(reduce(vcat, (y, ŷ))) confmat = zeros(Int64, n, n) for (predicted, actual) in zip(ŷ, y) @inbounds @fastmath confmat[predicted, actual] += 1 end return confmat end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
26855
""" validate(its; kwargs...) Test the validity of an estimated interrupted time series analysis. # Arguments - `its::InterruptedTimeSeries`: an interrupted time seiries estimator. # Keywords - `n::Int`: number of times to simulate a confounder. - `low::Float64`=0.15: minimum proportion of data points to include before or after the tested break in the Wald supremum test. - `high::Float64=0.85`: maximum proportion of data points to include before or after the tested break in the Wald supremum test. # Notes This method coducts a Chow Test, a Wald supremeum test, and tests the model's sensitivity to confounders. The Chow Test tests for structural breaks in the covariates between the time before and after the event. p-values represent the proportion of times the magnitude of the break in a covariate would have been greater due to chance. Lower p-values suggest a higher probability the event effected the covariates and they cannot provide unbiased counterfactual predictions. The Wald supremum test finds the structural break with the highest Wald statistic. If this is not the same as the hypothesized break, it could indicate an anticipation effect, a confounding event, or that the intervention or policy took place in multiple phases. p-values represent the proportion of times we would see a larger Wald statistic if the data points were randomly allocated to pre and post-event periods for the predicted structural break. Ideally, the hypothesized break will be the same as the predicted break and it will also have a low p-value. The omitted predictors test adds normal random variables with uniform noise as predictors. If the included covariates are good predictors of the counterfactual outcome, adding irrelevant predictors should not have a large effect on the predicted counterfactual outcomes or the estimated effect. This method does not implement the second test in Baicker and Svoronos because the estimator in this package models the relationship between covariates and the outcome and uses an extreme learning machine instead of linear regression, so variance in the outcome across different bins is not much of an issue. # References For more details on the assumptions and validity of interrupted time series designs, see: Baicker, Katherine, and Theodore Svoronos. Testing the validity of the single interrupted time series design. No. w26080. National Bureau of Economic Research, 2019. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> X₀, Y₀, X₁, Y₁ = rand(100, 5), rand(100), rand(10, 5), rand(10) julia> m1 = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁) julia> estimate_causal_effect!(m1) julia> validate(m1) ``` """ function validate(its::InterruptedTimeSeries; n=1000, low=0.15, high=0.85) if all(isnan, its.causal_effect) throw(ErrorException("call estimate_causal_effect! before calling validate")) end return covariate_independence(its; n=n), sup_wald(its; low=low, high=high, n=n), omitted_predictor(its; n=n) end """ validate(m; kwargs) # Arguments - `m::Union{CausalEstimator, Metalearner}`: model to validate/test the assumptions of. # Keywords - `devs=::Any`: iterable of deviations from which to generate noise to simulate violations of the counterfactual consistency assumption. - `num_iterations=10::Int: number of times to simulate a violation of the counterfactual consistency assumption.` - `min::Float64`=1.0e-6: minimum probability of treatment for the positivity assumption. - `high::Float64=1-min`: maximum probability of treatment for the positivity assumption. # Notes This method tests the counterfactual consistency, exchangeability, and positivity assumptions required for causal inference. It should be noted that consistency and exchangeability are not directly testable, so instead, these tests do not provide definitive evidence of a violation of these assumptions. To probe the counterfactual consistency assumption, we simulate counterfactual outcomes that are different from the observed outcomes, estimate models with the simulated counterfactual outcomes, and take the averages. If the outcome is continuous, the noise for the simulated counterfactuals is drawn from N(0, dev) for each element in devs, otherwise the default is 0.25, 0.5, 0.75, and 1.0 standard deviations from the mean outcome. For discrete variables, each outcome is replaced with a different value in the range of outcomes with probability ϵ for each ϵ in devs, otherwise the default is 0.025, 0.05, 0.075, 0.1. If the average estimate for a given level of violation differs greatly from the effect estimated on the actual data, then the model is very sensitive to violations of the counterfactual consistency assumption for that level of violation. Next, this methods tests the model's sensitivity to a violation of the exchangeability assumption by calculating the E-value, which is the minimum strength of association, on the risk ratio scale, that an unobserved confounder would need to have with the treatment and outcome variable to fully explain away the estimated effect. Thus, higher E-values imply the model is more robust to a violation of the exchangeability assumption. Finally, this method tests the positivity assumption by estimating propensity scores. Rows in the matrix are levels of covariates that have a zero probability of treatment. If the matrix is empty, none of the observations have an estimated zero probability of treatment, which implies the positivity assumption is satisfied. # References For a thorough review of casual inference assumptions see: Hernan, Miguel A., and James M. Robins. Causal inference what if. Boca Raton: Taylor and Francis, 2024. For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. # Examples ```julia julia> x, t, y = rand(100, 5), Float64.([rand()<0.4 for i in 1:100]), vec(rand(1:100, 100, 1)) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> validate(g_computer) ``` """ function validate(m, devs; iterations=10, min=1.0e-6, max=1.0 - min) if all(isnan, m.causal_effect) throw(ErrorException("call estimate_causal_effect! before calling validate")) end return counterfactual_consistency(m, devs, iterations), exchangeability(m), positivity(m, min, max) end function validate(m; iterations=10, min=1.0e-6, max=1.0 - min) if var_type(m.Y) isa Continuous devs = 0.25, 0.5, 0.75, 1.0 else devs = 0.025, 0.05, 0.075, 0.1 end return validate(m, devs; iterations=iterations, min=min, max=max) end """ covariate_independence(its; kwargs..) Test for independence between covariates and the event or intervention. # Arguments - `its::InterruptedTImeSeries`: an interrupted time series estimator. # Keywords - `n::Int`: number of permutations for assigning observations to the pre and post-treatment periods. This is a Chow Test for covariates with p-values estimated via randomization inference, which does not assume a distribution for the outcome variable. The p-values are the proportion of times randomly assigning observations to the pre or post-intervention period would have a larger estimated effect on the the slope of the covariates. The lower the p-values, the more likely it is that the event/intervention effected the covariates and they cannot provide an unbiased prediction of the counterfactual outcomes. For more information on using a Chow Test to test for structural breaks see: Baicker, Katherine, and Theodore Svoronos. Testing the validity of the single interrupted time series design. No. w26080. National Bureau of Economic Research, 2019. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> x₀, y₀, x₁, y₁ = (Float64.(rand(1:5, 100, 5)), randn(100), rand(1:5, (10, 5)), randn(10)) julia> its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) julia> estimate_causal_effect!(its) julia> covariate_independence(its) ``` """ function covariate_independence(its::InterruptedTimeSeries; n=1000) x₀ = reduce(hcat, (its.X₀[:, 1:(end - 1)], zeros(size(its.X₀, 1)))) x₁ = reduce(hcat, (its.X₁[:, 1:(end - 1)], ones(size(its.X₁, 1)))) x = reduce(vcat, (x₀, x₁)) results = Dict{String, Float64}() # Estimate a linear regression with each covariate as a dependent variable and all other # covariates and time as independent variables for i in axes(x, 2) new_x, y = x[:, 1:end .!= i], x[:, i] β = last(new_x \ y) p = p_val(new_x, y, β; n=n) results["Column " * string(i) * " p-value"] = p end return results end """ omitted_predictor(its; kwargs...) See how an omitted predictor/variable could change the results of an interrupted time series analysis. # Arguments - `its::InterruptedTImeSeries`: interrupted time seiries estimator. # Keywords - `n::Int`: number of times to simulate a confounder. # Notes This method reestimates interrupted time series models with uniform random variables. If the included covariates are good predictors of the counterfactual outcome, adding a random variable as a covariate should not have a large effect on the predicted counterfactual outcomes and therefore the estimated average effect. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> x₀, y₀, x₁, y₁ = (Float64.(rand(1:5, 100, 5)), randn(100), rand(1:5, (10, 5)), randn(10)) julia> its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) julia> estimate_causal_effect!(its) julia> omitted_predictor(its) ``` """ function omitted_predictor(its::InterruptedTimeSeries; n=1000) if all(isnan, its.causal_effect) throw(ErrorException("call estimate_causal_effect! before calling omittedvariable")) end its_copy = deepcopy(its) biased_effects = Vector{Float64}(undef, n) results = Dict{String,Float64}() for i in 1:n its_copy.X₀ = reduce(hcat, (its.X₀, rand(size(its.X₀, 1)))) its_copy.X₁ = reduce(hcat, (its.X₁, rand(size(its.X₁, 1)))) biased_effects[i] = mean(estimate_causal_effect!(its_copy)) end biased_effects = sort(biased_effects) results["Minimum Biased Effect/Original Effect"] = biased_effects[1] results["Mean Biased Effect/Original Effect"] = mean(biased_effects) results["Maximum Biased Effect/Original Effect"] = biased_effects[n] median = ifelse( n % 2 === 1, biased_effects[Int(ceil(n / 2))], mean([biased_effects[Int(n / 2)], biased_effects[Int(n / 2) + 1]]), ) results["Median Biased Effect/Original Effect"] = median return results end """ sup_wald(its; kwargs) Check if the predicted structural break is the hypothesized structural break. # Arguments - `its::InterruptedTimeSeries`: interrupted time seiries estimator. # Keywords - `n::Int`: number of times to simulate a confounder. - `low::Float64`=0.15: minimum proportion of data points to include before or after the tested break in the Wald supremum test. - `high::Float64=0.85`: maximum proportion of data points to include before or after the tested break in the Wald supremum test. # Notes This method conducts Wald tests and identifies the structural break with the highest Wald statistic. If this break is not the same as the hypothesized break, it could indicate an anticipation effect, confounding by some other event or intervention, or that the intervention or policy took place in multiple phases. p-values are estimated using approximate randomization inference and represent the proportion of times we would see a larger Wald statistic if the data points were randomly allocated to pre and post-event periods for the predicted structural break. # References For more information on using a Chow Test to test for structural breaks see: Baicker, Katherine, and Theodore Svoronos. Testing the validity of the single interrupted time series design. No. w26080. National Bureau of Economic Research, 2019. For a primer on randomization inference see: https://www.mattblackwell.org/files/teaching/s05-fisher.pdf # Examples ```julia julia> x₀, y₀, x₁, y₁ = (Float64.(rand(1:5, 100, 5)), randn(100), rand(1:5, (10, 5)), randn(10)) julia> its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) julia> estimate_causal_effect!(its) julia> sup_wald(its) ``` """ function sup_wald(its::InterruptedTimeSeries; low=0.15, high=0.85, n=1000) hypothesized_break, current_break, wald = size(its.X₀, 1), size(its.X₀, 1), 0.0 high_idx, low_idx = Int(floor(high * size(its.X₀, 1))), Int(ceil(low * size(its.X₀, 1))) x, y = reduce(vcat, (its.X₀, its.X₁)), reduce(vcat, (its.Y₀, its.Y₁)) t = reduce(vcat, (zeros(size(its.X₀, 1)), ones(size(its.X₁, 1)))) best_x = reduce(hcat, (x, t)) best_β = last(best_x \ y) # Set each time as a potential break and calculate its Wald statistic for idx in low_idx:high_idx t = reduce(vcat, (zeros(idx), ones(size(x, 1) - idx))) new_x = reduce(hcat, (x, t)) β, ŷ = @fastmath new_x \ y, new_x * (new_x \ y) se = @fastmath sqrt(1 / (size(x, 1) - 2)) * (sum(y .- ŷ)^2 / sum(t .- mean(t))^2) wald_candidate = last(β) / se if wald_candidate > wald current_break, wald, best_x, best_β = idx, wald_candidate, new_x, best_β end end p = p_val(best_x, y, best_β; n=n, two_sided=true) return Dict( "Hypothesized Break Point" => hypothesized_break, "Predicted Break Point" => current_break, "Wald Statistic" => wald, "p-value" => p, ) end """ p_val(x, y, β; kwargs...) Estimate the p-value for the hypothesis that an event had a statistically significant effect on the slope of a covariate using randomization inference. # Arguments - `x::Array{<:Real}`: covariates. - `y::Array{<:Real}`: outcome. - `β::Array{<:Real}`=0.15: fitted weights. # Keywords - `two_sided::Bool=false`: whether to conduct a one-sided hypothesis test. # Examples ```julia julia> x, y, β = reduce(hcat, (float(rand(0:1, 10)), ones(10))), rand(10), 0.5 julia> p_val(x, y, β) julia> p_val(x, y, β; n=100, two_sided=true) ``` """ function p_val(x, y, β; n=1000, two_sided=false) x_copy, null = deepcopy(x), Vector{Float64}(undef, n) min_x, max_x = minimum(x_copy[:, end]), maximum(x_copy[:, end]) # Run OLS with random treatment vectors to generate a counterfactual distribution @simd for i in 1:n if var_type(x_copy[:, end]) isa Continuous @inbounds x_copy[:, end] = (max_x - min_x) * rand(length(x_copy[:, end])) .+ min_x else @inbounds x_copy[:, end] = float(rand(min_x:max_x, size(x, 1))) end null[i] = last(x_copy \ y) end # Wald test is only one sided p = two_sided ? length(null[β .< null]) / n : length(null[abs(β) .< abs.(null)]) / n return p end """ counterfactual_consistency(m; kwargs...) # Arguments - `m::Union{CausalEstimator, Metalearner}`: model to validate/test the assumptions of. # Keywords - `num_devs=(0.25, 0.5, 0.75, 1.0)::Tuple`: number of standard deviations from which to generate noise from a normal distribution to simulate violations of the counterfactual consistency assumption. - `num_iterations=10::Int: number of times to simulate a violation of the counterfactual consistency assumption.` # Notes Examine the counterfactual consistency assumption. First, this function simulates counterfactual outcomes that are offset from the outcomes in the dataset by random scalars drawn from a N(0, num_std_dev). Then, the procedure is repeated num_iterations times and averaged. If the model is a metalearner, then the estimated individual treatment effects are averaged and the mean CATE is averaged over all the iterations, otherwise the estimated treatment effect is averaged over the iterations. The previous steps are repeated for each element in num_devs. # Examples ```julia julia> x, t = rand(100, 5), Float64.([rand()<0.4 for i in 1:100] julia> y = vec(rand(1:100, 100, 1))) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> counterfactual_consistency(g_computer) ``` """ function counterfactual_consistency(model, devs, iterations) counterfactual_model = deepcopy(model) avg_counterfactual_effects = Dict{String,Float64}() for dev in devs key = string(dev) * " Standard Deviations from Observed Outcomes" avg_counterfactual_effects[key] = 0.0 # Averaging multiple iterations of random violatons for each std dev for iteration in 1:iterations counterfactual_model.Y = simulate_counterfactual_violations(model.Y, dev) estimate_causal_effect!(counterfactual_model) if counterfactual_model isa Metalearner avg_counterfactual_effects[key] += mean(counterfactual_model.causal_effect) else avg_counterfactual_effects[key] += counterfactual_model.causal_effect end end avg_counterfactual_effects[key] /= iterations end return avg_counterfactual_effects end """ simulate_counterfactual_violations(y, dev) # Arguments - `y::Vector{<:Real}`: vector of real-valued outcomes. - `dev::Float64`: deviation of the observed outcomes from the true counterfactual outcomes. # Examples ```julia julia> x, t, y = rand(100, 5), Float64.([rand()<0.4 for i in 1:100]), vec(rand(1:100, 100, 1)) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> simulate_counterfactual_violations(g_computer) -0.7748591231872396 ``` """ function simulate_counterfactual_violations(y::Vector{<:Real}, dev::Float64) min_y, max_y = minimum(y), maximum(y) if var_type(y) isa Continuous violations = dev .* randn(length(y)) counterfactual_Y = y .+ (violations .* y) else counterfactual_Y = ifelse.(rand() < dev, Float64(rand(min_y:max_y)), y) end return counterfactual_Y end """ exchangeability(model) Test the sensitivity of a G-computation or doubly robust estimator or metalearner to a violation of the exchangeability assumption. # References For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. # Examples ```julia julia> x, t = rand(100, 5), Float64.([rand()<0.4 for i in 1:100] julia> y = vec(rand(1:100, 100, 1))) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> e_value(g_computer) ``` """ exchangeability(model) = e_value(model) """ e_value(model) Test the sensitivity of an estimator to a violation of the exchangeability assumption. # References For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. # Examples ```julia julia> x, t = rand(100, 5), Float64.([rand()<0.4 for i in 1:100] julia> y = vec(rand(1:100, 100, 1))) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> e_value(g_computer) ``` """ function e_value(model) rr = risk_ratio(model) if rr > 1 return @fastmath rr + sqrt(rr * (rr - 1)) else rr🥰 = @fastmath 1 / rr return @fastmath rr🥰 + sqrt(rr🥰 * (rr🥰 - 1)) end end """ binarize(x, cutoff) Convert a vector of counts or a continuous vector to a binary vector. # Arguments - `x::Any`: interable of numbers to binarize. - `x::Any`: threshold after which numbers are converted to 1 and befrore which are converted to 0. # Examples ```jldoctest julia> CausalELM.binarize([1, 2, 3], 2) 3-element Vector{Int64}: 0 0 1 ``` """ function binarize(x, cutoff) if var_type(x) isa Binary return x else x[x .<= cutoff] .= 0 x[x .> cutoff] .= 1 end return x end """ risk_ratio(model) Calculate the risk ratio for an estimated model. # Notes If the treatment variable is not binary and the outcome variable is not continuous then the treatment variable will be binarized. # References For more information on how other quantities of interest are converted to risk ratios see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. # Examples ```julia julia> x, t = rand(100, 5), Float64.([rand()<0.4 for i in 1:100] julia> y = vec(rand(1:100, 100, 1))) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> risk_ratio(g_computer) ``` """ risk_ratio(mod) = risk_ratio(var_type(mod.T), mod) # First we dispatch based on whether the treatment variable is binary or not # If it is binary, we call the risk_ratio method based on the type of outcome variable risk_ratio(::Binary, mod) = risk_ratio(Binary(), var_type(mod.Y), mod) # If the treatment variable is not binary this method gets called function risk_ratio(::Nonbinary, mod) # When the outcome variable is continuous, we can treat it the same as if the treatment # variable was binary because we don't use the treatment to calculate the risk ratio if var_type(mod.Y) isa Continuous return risk_ratio(Binary(), Continuous(), mod) # Otherwise, we convert the treatment variable to a binary variable and then # dispatch based on the type of outcome variable else original_T, binary_T = mod.T, binarize(mod.T, mean(mod.T)) mod.T = binary_T rr = risk_ratio(Binary(), mod) # Reset to the original treatment variable mod.T = original_T return rr end end # This approximates the risk ratio for a binary treatment with a binary outcome function risk_ratio(::Binary, ::Binary, mod) Xₜ, Xᵤ = mod.X[mod.T .== 1, :], mod.X[mod.T .== 0, :] Xₜ, Xᵤ = reduce(hcat, (Xₜ, ones(size(Xₜ, 1)))), reduce(hcat, (Xᵤ, ones(size(Xᵤ, 1)))) # For algorithms that use one model to estimate the outcome if hasfield(typeof(mod), :ensemble) return @fastmath (mean(predict(mod.ensemble, Xₜ)) / mean(predict(mod.ensemble, Xᵤ))) # For models that use separate models for outcomes in the treatment and control group else hasfield(typeof(mod), :μ₀) Xₜ, Xᵤ = mod.X[mod.T .== 1, :], mod.X[mod.T .== 0, :] return @fastmath mean(predict(mod.μ₁, Xₜ)) / mean(predict(mod.μ₀, Xᵤ)) end end # This approximates the risk ratio with a binary treatment and count or categorical outcome function risk_ratio(::Binary, ::Count, mod) Xₜ, Xᵤ = mod.X[mod.T .== 1, :], mod.X[mod.T .== 0, :] m, n = size(Xₜ, 1), size(Xᵤ, 1) # The number of obeservations in each group Xₜ, Xᵤ = reduce(hcat, (Xₜ, ones(m))), reduce(hcat, (Xᵤ, ones(n))) # For estimators with a single model of the outcome variable if hasfield(typeof(mod), :ensemble) return @fastmath (sum(predict(mod.ensemble, Xₜ)) / m) / (sum(predict(mod.ensemble, Xᵤ)) / n) # For models that use separate models for outcomes in the treatment and control group elseif hasfield(typeof(mod), :μ₀) Xₜ, Xᵤ = mod.X[mod.T .== 1, :], mod.X[mod.T .== 0, :] return @fastmath mean(predict(mod.μ₁, Xₜ)) / mean(predict(mod.μ₀, Xᵤ)) else learner = ELMEnsemble( reduce(hcat, (mod.X, mod.T)), mod.Y, mod.sample_size, mod.num_machines, mod.num_feats, mod.num_neurons, mod.activation ) fit!(learner) @fastmath mean(predict(learner, Xₜ)) / mean(predict(learner, Xᵤ)) end end # This approximates the risk ratio when the outcome variable is continuous function risk_ratio(::Binary, ::Continuous, mod) type = typeof(mod) # We use the estimated effect if using DML because it uses linear regression d = hasfield(type, :coefficients) ? mod.causal_effect : mean(mod.Y) / sqrt(var(mod.Y)) return @fastmath exp(0.91 * d) end """ positivity(model, [,min], [,max]) Find likely violations of the positivity assumption. # Notes This method uses an extreme learning machine or regularized extreme learning machine to estimate probabilities of treatment. The returned matrix, which may be empty, are the covariates that have a (near) zero probability of treatment or near zero probability of being assigned to the control group, whith their entry in the last column being their estimated treatment probability. In other words, they likely violate the positivity assumption. # Arguments - `model::Union{CausalEstimator, Metalearner}`: a model to validate/test the assumptions of. - `min::Float64`=1.0e-6: minimum probability of treatment for the positivity assumption. - `high::Float64=1-min`: the maximum probability of treatment for the positivity assumption. # Examples ```julia julia> x, t = rand(100, 5), Float64.([rand()<0.4 for i in 1:100] julia> y = vec(rand(1:100, 100, 1))) julia> g_computer = GComputation(x, t, y, temporal=false) julia> estimate_causal_effect!(g_computer) julia> positivity(g_computer) ``` """ function positivity(model, min=1.0e-6, max=1 - min) ps_mod = ELMEnsemble( model.X, model.T, model.sample_size, model.num_machines, model.num_feats, model.num_neurons, model.activation ) fit!(ps_mod) propensity_scores = predict(ps_mod, model.X) # Observations that have a zero probability of treatment or control assignment return reduce( hcat, ( model.X[propensity_scores .<= min .|| propensity_scores .>= max, :], propensity_scores[propensity_scores .<= min .|| propensity_scores .>= max], ), ) end function positivity(model::XLearner, min=1.0e-6, max=1 - min) # Observations that have a zero probability of treatment or control assignment return reduce( hcat, ( model.X[model.ps .<= min .|| model.ps .>= max, :], model.ps[model.ps .<= min .|| model.ps .>= max], ), ) end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
8030
using Random: shuffle using CausalELM: mean, var_type, clip_if_binary """ ExtremeLearner(X, Y, hidden_neurons, activation) Construct an ExtremeLearner for fitting and prediction. # Notes While it is possible to use an ExtremeLearner for regression, it is recommended to use RegularizedExtremeLearner, which imposes an L2 penalty, to reduce multicollinearity. # References For more details see: Huang, Guang-Bin, Qin-Yu Zhu, and Chee-Kheong Siew. "Extreme learning machine: theory and applications." Neurocomputing 70, no. 1-3 (2006): 489-501. # Examples ```julia julia> x, y = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0], [0.0, 1.0, 0.0, 1.0] julia> m1 = ExtremeLearner(x, y, 10, σ) ``` """ mutable struct ExtremeLearner X::Array{Float64} Y::Array{Float64} training_samples::Int64 features::Int64 hidden_neurons::Int64 activation::Function __fit::Bool weights::Array{Float64} β::Array{Float64} H::Array{Float64} counterfactual::Array{Float64} function ExtremeLearner(X, Y, hidden_neurons, activation) return new(X, Y, size(X, 1), size(X, 2), hidden_neurons, activation, false) end end """ ELMEnsemble(X, Y, sample_size, num_machines, num_neurons) Initialize a bagging ensemble of extreme learning machines. # Arguments - `X::Array{Float64}`: array of features for predicting labels. - `Y::Array{Float64}`: array of labels to predict. - `sample_size::Integer`: how many data points to use for each extreme learning machine. - `num_machines::Integer`: how many extreme learning machines to use. - `num_feats::Integer`: how many features to consider for eac exreme learning machine. - `num_neurons::Integer`: how many neurons to use for each extreme learning machine. - `activation::Function`: activation function to use for the extreme learning machines. # Notes ELMEnsemble uses the same bagging approach as random forests when the labels are continuous but uses the average predicted probability, rather than voting, for classification. # Examples ```julia julia> X, Y = rand(100, 5), rand(100) julia> m1 = ELMEnsemble(X, Y, 10, 50, 5, 5, CausalELM.relu) ``` """ mutable struct ELMEnsemble X::Array{Float64} Y::Array{Float64} elms::Array{ExtremeLearner} feat_indices::Vector{Vector{Int64}} end function ELMEnsemble( X::Array{Float64}, Y::Array{Float64}, sample_size::Integer, num_machines::Integer, num_feats::Integer, num_neurons::Integer, activation::Function ) # Sampling from the data with replacement indices = [rand(1:length(Y), sample_size) for i ∈ 1:num_machines] feat_indices = [shuffle(1:size(X, 2))[1:num_feats] for i ∈ 1:num_machines] xs = [X[indices[i], feat_indices[i]] for i ∈ 1:num_machines] ys = [Y[indices[i]] for i ∈ 1:num_machines] elms = [ExtremeLearner(xs[i], ys[i], num_neurons, activation) for i ∈ eachindex(xs)] return ELMEnsemble(X, Y, elms, feat_indices) end """ fit!(model) Fit an ExtremeLearner to the data. # References For more details see: Huang, Guang-Bin, Qin-Yu Zhu, and Chee-Kheong Siew. "Extreme learning machine: theory and applications." Neurocomputing 70, no. 1-3 (2006): 489-501. # Examples ```julia julia> x, y = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0], [0.0, 1.0, 0.0, 1.0] julia> m1 = ExtremeLearner(x, y, 10, σ) ``` """ function fit!(model::ExtremeLearner) set_weights_biases(model) model.__fit = true model.β = model.H\model.Y return model.β end """ fit!(model) Fit an ensemble of ExtremeLearners to the data. # Arguments - `model::ELMEnsemble`: ensemble of ExtremeLearners to fit. # Notes This uses the same bagging approach as random forests when the labels are continuous but uses the average predicted probability, rather than voting, for classification. # Examples ```julia julia> X, Y = rand(100, 5), rand(100) julia> m1 = ELMEnsemble(X, Y, 10, 50, 5, CausalELM.relu) julia> fit!(m1) ``` """ function fit!(model::ELMEnsemble) Threads.@threads for elm in model.elms fit!(elm) end end """ predict(model, X) Use an ExtremeLearningMachine or ELMEnsemble to make predictions. # Notes If using an ensemble to make predictions, this method returns a maxtirs where each row is a prediction and each column is a model. # References For more details see: Huang G-B, Zhu Q-Y, Siew C. Extreme learning machine: theory and applications. Neurocomputing. 2006;70:489–501. https://doi.org/10.1016/j.neucom.2005.12.126 # Examples ```julia julia> x, y = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0], [0.0, 1.0, 0.0, 1.0] julia> m1 = ExtremeLearner(x, y, 10, σ) julia> fit!(m1, sigmoid) julia> predict(m1, [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0]) julia> m2 = ELMEnsemble(X, Y, 10, 50, 5, CausalELM.relu) julia> fit!(m2) julia> predict(m2) ``` """ function predict(model::ExtremeLearner, X) if !model.__fit throw(ErrorException("run fit! before calling predict")) end predictions = model.activation(X * model.weights) * model.β return clip_if_binary(predictions, var_type(model.Y)) end @inline function predict(model::ELMEnsemble, X) predictions = reduce( hcat, [predict(model.elms[i], X[:, model.feat_indices[i]]) for i ∈ 1:length(model.elms)] ) return vec(mapslices(mean, predictions, dims=2)) end """ predict_counterfactual!(model, X) Use an ExtremeLearningMachine to predict the counterfactual. # Notes This should be run with the observed covariates. To use synthtic data for what-if scenarios use predict. See also [`predict`](@ref). # Examples ```julia julia> x, y = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0], [0.0, 1.0, 0.0, 1.0] julia> m1 = ExtremeLearner(x, y, 10, σ) julia> f1 = fit(m1, sigmoid) julia> predict_counterfactual!(m1, [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0]) ``` """ function predict_counterfactual!(model::ExtremeLearner, X) model.counterfactual = predict(model, X) return model.counterfactual end """ placebo_test(model) Conduct a placebo test. # Notes This method makes predictions for the post-event or post-treatment period using data in the pre-event or pre-treatment period and the post-event or post-treament. If there is a statistically significant difference between these predictions the study design may be flawed. Due to the multitude of significance tests for time series data, this function returns the predictions but does not test for statistical significance. # Examples ```julia julia> x, y = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0], [0.0, 1.0, 0.0, 1.0] julia> m1 = ExtremeLearner(x, y, 10, σ) julia> f1 = fit(m1, sigmoid) julia> predict_counterfactual(m1, [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0]) julia> placebo_test(m1) ``` """ function placebo_test(model::ExtremeLearner) m = "Use predict_counterfactual! to estimate a counterfactual before using placebo_test" if !isdefined(model, :counterfactual) throw(ErrorException(m)) end return predict(model, model.X), model.counterfactual end """ set_weights_biases(model) Calculate the weights and biases for an extreme learning machine. # Notes Initialization is done using uniform Xavier initialization. # References For details see; Huang, Guang-Bin, Qin-Yu Zhu, and Chee-Kheong Siew. "Extreme learning machine: theory and applications." Neurocomputing 70, no. 1-3 (2006): 489-501. # Examples ```julia julia> m1 = RegularizedExtremeLearner(x, y, 10, σ) julia> set_weights_biases(m1) ``` """ function set_weights_biases(model::ExtremeLearner) a, b = -1, 1 model.weights = @fastmath a .+ ((b - a) .* rand(model.features, model.hidden_neurons)) return model.H = @fastmath model.activation((model.X * model.weights)) end function Base.show(io::IO, model::ExtremeLearner) return print( io, "Extreme Learning Machine with ", model.hidden_neurons, " hidden neurons" ) end function Base.show(io::IO, model::ELMEnsemble) return print( io, "Extreme Learning Machine Ensemble with ", length(model.elms), " learners" ) end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
4979
using Random: shuffle """Abstract type used to dispatch risk_ratio on nonbinary treatments""" abstract type Nonbinary end """Type used to dispatch risk_ratio on binary treatments""" struct Binary end """Type used to dispatch risk_ratio on count treatments""" struct Count <: Nonbinary end """Type used to dispatch risk_ratio on continuous treatments""" struct Continuous <: Nonbinary end """ var_type(x) Determine the type of variable held by a vector. # Examples ```jldoctest julia> CausalELM.var_type([1, 2, 3, 2, 3, 1, 1, 3, 2]) CausalELM.Count() ``` """ function var_type(x::Array{<:Real}) x_set = Set(x) if x_set == Set([0, 1]) || x_set == Set([0]) || x_set == Set([1]) return Binary() elseif x_set == Set(round.(x_set)) return Count() else return Continuous() end end """ mean(x) Calculate the mean of a vector. # Examples ```jldoctest julia> CausalELM.mean([1, 2, 3, 4]) 2.5 ``` """ mean(x) = sum(x) / size(x, 1) """ var(x) Calculate the (sample) mean of a vector. # Examples ```jldoctest julia> CausalELM.var([1, 2, 3, 4]) 1.6666666666666667 ``` """ var(x) = sum((x .- mean(x)) .^ 2) / (length(x) - 1) """ one_hot_encode(x) One hot encode a categorical vector for multiclass classification. # Examples ```jldoctest julia> CausalELM.one_hot_encode([1, 2, 3, 4, 5]) 5×5 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 ``` """ function one_hot_encode(x) one_hot = permutedims(float(unique(x) .== reshape(x, (1, size(x, 1))))), (2, 1) return one_hot[1] end """ clip_if_binary(x, var) Constrain binary values between 1e-7 and 1 - 1e-7, otherwise return the original values. # Arguments - `x::Array`: array to clip if it is binary. - `var`: type of x based on calling var_type. See also [`var_type`](@ref). # Examples ```jldoctest julia> CausalELM.clip_if_binary([1.2, -0.02], CausalELM.Binary()) 2-element Vector{Float64}: 1.0 0.0 julia> CausalELM.clip_if_binary([1.2, -0.02], CausalELM.Count()) 2-element Vector{Float64}: 1.2 -0.02 ``` """ clip_if_binary(x::Array{<:Real}, var) = var isa Binary ? clamp.(x, 0.0, 1.0) : x """ model_config(effect_type) Generate fields common to all CausalEstimator, Metalearner, and InterruptedTimeSeries structs. # Arguments - `effect_type::String`: "average_effect" or "individual_effect" to define fields for either models that estimate average effects or the CATE. # Examples ```julia julia> struct TestStruct CausalELM.@model_config average_effect end julia> TestStruct("ATE", false, "classification", true, relu, F1, 2, 10, 5, 100, 5, 5, 0.25) TestStruct("ATE", false, "classification", true, relu, F1, 2, 10, 5, 100, 5, 5, 0.25) ``` """ macro model_config(effect_type) msg = "the effect type must either be average_effect or individual_effect" if string(effect_type) == "average_effect" field_type = :Float64 elseif string(effect_type) == "individual_effect" field_type = :(Array{Float64}) else throw(ArgumentError(msg)) end fields = quote quantity_of_interest::String temporal::Bool task::String activation::Function sample_size::Integer num_machines::Integer num_feats::Integer num_neurons::Integer causal_effect::$field_type end return esc(fields) end """ standard_input_data() Generate fields common to all CausalEstimators except DoubleMachineLearning and all Metalearners except RLearner and DoublyRobustLearner. # Examples ```julia julia> struct TestStruct CausalELM.@standard_input_data end julia> TestStruct([5.2], [0.8], [0.96]) TestStruct([5.2], [0.8], [0.96]) ``` """ macro standard_input_data() inputs = quote X::Array{Float64} T::Array{Float64} Y::Array{Float64} end return esc(inputs) end """ generate_folds(X, T, Y, folds) Create folds for cross validation. # Examples ```jldoctest julia> xfolds, tfolds, yfolds = CausalELM.generate_folds(zeros(4, 2), zeros(4), ones(4), 2) ([[0.0 0.0], [0.0 0.0; 0.0 0.0; 0.0 0.0]], [[0.0], [0.0, 0.0, 0.0]], [[1.0], [1.0, 1.0, 1.0]]) ``` """ function generate_folds(X, T, Y, folds) msg = """the number of folds must be less than the number of observations""" n = length(Y) if folds >= n throw(ArgumentError(msg))end x_folds = Array{Array{Float64, 2}}(undef, folds) t_folds = Array{Array{Float64, 1}}(undef, folds) y_folds = Array{Array{Float64, 1}}(undef, folds) # Indices to start and stop for each fold stops = round.(Int, range(; start=1, stop=n, length=folds + 1)) # Indices to use for making folds indices = [s:(e - (e < n) * 1) for (s, e) in zip(stops[1:(end - 1)], stops[2:end])] for (i, idx) in enumerate(indices) x_folds[i], t_folds[i], y_folds[i] = X[idx, :], T[idx], Y[idx] end return x_folds, t_folds, y_folds end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
423
using Test using Aqua using Documenter using CausalELM include("test_activation.jl") include("test_models.jl") include("test_metrics.jl") include("test_estimators.jl") include("test_metalearners.jl") include("test_inference.jl") include("test_model_validation.jl") include("test_utilities.jl") Aqua.test_all(CausalELM) DocMeta.setdocmeta!(CausalELM, :DocTestSetup, :(using CausalELM); recursive=true) doctest(CausalELM)
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
4648
using Test using CausalELM @testset "Binary Step Activation" begin # Single numbers @test binary_step(-1000.0) == 0 @test binary_step(-0.00001) == 0 @test binary_step(0.0) == 1 @test binary_step(0.00001) == 1 @test binary_step(100.0) == 1 # Vectors @test binary_step([-100.0]) == [0] @test binary_step([-100.0, -100.0, -100.0]) == [0, 0, 0] @test binary_step([-0.00001, -0.00001, -0.00001]) == [0, 0, 0] @test binary_step([0.0, 0.0, 0.0]) == [1, 1, 1] @test binary_step([0.00001, 0.00001, 0.00001]) == [1, 1, 1] @test binary_step([100.0, 100.0, 100.0]) == [1, 1, 1] @test binary_step([-1000.0, 100.0, 1.0, 0.0, -0.001, -3]) == [0, 1, 1, 1, 0, 0] end @testset "Sigmoid Activation" begin @test σ(1.0) == 0.7310585786300049 @test σ(0.0) == 0.5 @test σ(-1.0) == 0.2689414213699951 @test σ(100.0) == 1 @test σ(-100.0) == 3.720075976020836e-44 @test σ([1.0]) == [0.7310585786300049] @test σ([1.0, 0.0]) == [0.7310585786300049, 0.5] @test σ([1.0, 0.0, -1.0]) == [0.7310585786300049, 0.5, 0.2689414213699951] @test σ([1.0, 0.0, -1.0, 100.0]) == [0.7310585786300049, 0.5, 0.2689414213699951, 1] @test σ([1.0, 0.0, -1.0, 100.0, -100.0]) == [0.7310585786300049, 0.5, 0.2689414213699951, 1, 3.720075976020836e-44] end @testset "tanh Activation" begin @test CausalELM.tanh([1.0]) == [0.7615941559557649] @test CausalELM.tanh([1.0, 0.0]) == [0.7615941559557649, 0.0] @test CausalELM.tanh([1.0, 0.0, -1.0]) == [0.7615941559557649, 0.0, -0.7615941559557649] @test CausalELM.tanh([1.0, 0.0, -1.0, 100.0]) == [0.7615941559557649, 0.0, -0.7615941559557649, 1.0] @test CausalELM.tanh([1.0, 0.0, -1.0, 100.0, -100.0]) == [0.7615941559557649, 0.0, -0.7615941559557649, 1.0, -1.0] end @testset "ReLU Activation" begin @test relu(1.0) == 1 @test relu(0.0) == 0 @test relu(-1.0) == 0 @test relu([1.0, 0.0, -1.0]) == [1, 0, 0] end @testset "Leaky ReLU Activation" begin @test leaky_relu(-1.0) == -0.01 @test leaky_relu(0.0) == 0 @test leaky_relu(1.0) == 1 @test leaky_relu([-1.0, 0.0, 1.0]) == [-0.01, 0, 1] end @testset "swish Activation" begin @test swish(1.0) == 0.7310585786300049 @test swish(0.0) == 0 @test swish(-1.0) == -0.2689414213699951 @test swish(5.0) == 4.966535745378576 @test swish(-5.0) == -0.03346425462142428 @test swish([1.0, 0.0, -1.0]) == [0.7310585786300049, 0, -0.2689414213699951] end @testset "softmax Activation" begin @test softmax(1.0) == 1.0 @test softmax(-1.0) == 1.0 @test sum(softmax([1.0, -0.5])) == 1.0 @test sum(softmax([1.0, 0])) == 1.0 @test vec(mapslices(sum, softmax(rand(3, 3)); dims=2)) ≈ [1, 1, 1] end @testset "softplus Activation" begin @test softplus(-1.0) == 0.3132616875182228 @test softplus(1.0) == 1.3132616875182228 @test softplus(0.0) == 0.6931471805599453 @test softplus(5.0) == 5.006715348489118 @test softplus(-5.0) == 0.006715348489118068 @test softplus([-1.0, 1.0, 0.0]) == [0.3132616875182228, 1.3132616875182228, 0.6931471805599453] end @testset "GeLU Activation" begin @test gelu(-1.0) == -0.15880800939172324 @test gelu(0.0) == 0 @test gelu(1.0) == 0.8411919906082768 @test gelu(5.0) == 4.999999770820381 @test gelu(-5.0) == -2.2917961972623857e-7 @test gelu([-1.0, 0.0, 1.0]) == [-0.15880800939172324, 0, 0.8411919906082768] end @testset "Gaussian Activation" begin @test gaussian(1.0) ≈ 0.36787944117144233 @test gaussian(-1.0) ≈ 0.36787944117144233 @test gaussian(0.0) ≈ 1.0 @test gaussian(-5.0) ≈ 1.3887943864964021e-11 @test gaussian(5.0) ≈ 1.3887943864964021e-11 @test gaussian([1.0, -1.0, 0.0]) ≈ [0.36787944117144233, 0.36787944117144233, 1.0] end @testset "hard_tanh Activation" begin @test hard_tanh(-2.0) == -1 @test hard_tanh(0.0) == 0 @test hard_tanh(2.0) == 1 @test hard_tanh([-1.0, 0.0, 1.0]) == [-1, 0, 1] end @testset "ELiSH Activation" begin @test elish(-5.0) == -0.006647754849484245 @test elish(-1.0) == -0.17000340156854793 @test elish(-0.5) == -0.1485506778836575 @test elish(0.5) == 0.3112296656009273 @test elish(1.0) == 0.7310585786300049 @test elish(5.0) == 4.966535745378576 @test elish([-5.0, -1.0, -0.5]) == [-0.006647754849484245, -0.17000340156854793, -0.1485506778836575] end @testset "Fourier Activation" begin @test fourier(1.0) ≈ 0.8414709848078965 @test fourier(0.0) == 0 @test fourier(-1.0) ≈ -0.8414709848078965 @test fourier([1.0, 0.0, -1.0]) ≈ [0.8414709848078965, 0, -0.8414709848078965] end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
4899
using Test using CausalELM using DataFrames include("../src/models.jl") x₀, y₀, x₁, y₁ = Float64.(rand(1:200, 100, 5)), rand(100), rand(10, 5), rand(10) its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) estimate_causal_effect!(its) # ITS with a DataFrame x₀_df, y₀_df = DataFrame(; x1=rand(100), x2=rand(100), x3=rand(100)), DataFrame(; y=rand(100)) x₁_df, y₁_df = DataFrame(; x1=rand(100), x2=rand(100), x3=rand(100)), DataFrame(; y=rand(100)) its_df = InterruptedTimeSeries(x₀_df, y₀_df, x₁_df, y₁_df) # No autoregressive term its_no_ar = InterruptedTimeSeries(x₀, y₀, x₁, y₁) estimate_causal_effect!(its_no_ar) x, t, y = rand(100, 5), rand(0:1, 100), vec(rand(1:100, 100, 1)) g_computer = GComputation(x, t, y; temporal=false) estimate_causal_effect!(g_computer) # Testing with a binary outcome g_computer_binary_out = GComputation(x, y, t; temporal=false) estimate_causal_effect!(g_computer_binary_out) # G-computation with a DataFrame x_df = DataFrame(; x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) t_df, y_df = DataFrame(; t=rand(0:1, 100)), DataFrame(; y=rand(100)) g_computer_df = GComputation(x_df, t_df, y_df) gcomputer_att = GComputation(x, t, y; quantity_of_interest="ATT", temporal=false) estimate_causal_effect!(gcomputer_att) # Make sure the data isn't shuffled g_computer_ts = GComputation( float.(hcat([1:10;], 11:20)), Float64.([rand() < 0.4 for i in 1:10]), rand(10) ) big_x, big_t, big_y = rand(10000, 8), rand(0:1, 10000), vec(rand(1:100, 10000, 1)) dm = DoubleMachineLearning(big_x, big_t, big_y) estimate_causal_effect!(dm) # Testing with a binary outcome dm_binary_out = DoubleMachineLearning(x, y, t) estimate_causal_effect!(dm_binary_out) # With dataframes instead of arrays dm_df = DoubleMachineLearning(x_df, t_df, y_df) # Test predicting residuals x_train, x_test = x[1:80, :], x[81:end, :] t_train, t_test = float(t[1:80]), float(t[81:end]) y_train, y_test = float(y[1:80]), float(y[81:end]) residual_predictor = DoubleMachineLearning(x, t, y, num_neurons=5) residuals = CausalELM.predict_residuals( residual_predictor, x_train, x_test, y_train, y_test, t_train, t_test ) @testset "Interrupted Time Series Estimation" begin @testset "Interrupted Time Series Structure" begin @test its.X₀ !== Nothing @test its.Y₀ !== Nothing @test its.X₁ !== Nothing @test its.Y₁ !== Nothing # No autocorrelation term @test its_no_ar.X₀ !== Nothing @test its_no_ar.Y₀ !== Nothing @test its_no_ar.X₁ !== Nothing @test its_no_ar.Y₁ !== Nothing # When initializing with a DataFrame @test its_df.X₀ !== Nothing @test its_df.Y₀ !== Nothing @test its_df.X₁ !== Nothing @test its_df.Y₁ !== Nothing end @testset "Interrupted Time Series Estimation" begin @test isa(its.causal_effect, Array) # Without autocorrelation @test isa(its_no_ar.causal_effect, Array) end end @testset "G-Computation" begin @testset "G-Computation Structure" begin @test g_computer.X !== Nothing @test g_computer.T !== Nothing @test g_computer.Y !== Nothing # Make sure temporal data isn't shuffled @test g_computer_ts.X[1, 1] === 1.0 @test g_computer_ts.X[2, 1] === 2.0 @test g_computer_ts.X[9, 2] === 19.0 @test g_computer_ts.X[10, 2] === 20.0 # G-computation Initialized with a DataFrame @test g_computer_df.X !== Nothing @test g_computer_df.T !== Nothing @test g_computer_df.Y !== Nothing end @testset "G-Computation Estimation" begin @test isa(g_computer.causal_effect, Float64) @test isa(g_computer_binary_out.causal_effect, Float64) # Check that the estimats for ATE and ATT are different @test g_computer.causal_effect !== gcomputer_att.causal_effect end end @testset "Double Machine Learning" begin @testset "Double Machine Learning Structure" begin @test dm.X !== Nothing @test dm.T !== Nothing @test dm.Y !== Nothing # Intialized with dataframes @test dm_df.X !== Nothing @test dm_df.T !== Nothing @test dm_df.Y !== Nothing end @testset "Generating Residuals" begin @test residuals[1] isa Vector @test residuals[2] isa Vector end @testset "Double Machine Learning Post-estimation Structure" begin @test dm.causal_effect isa Float64 end end @testset "Miscellaneous Tests" begin @testset "Quanities of Interest Errors" begin @test_throws ArgumentError GComputation(x, y, t, quantity_of_interest="abc") end @testset "Moving Averages" begin @test CausalELM.moving_average(Float64[]) isa Array{Float64} @test CausalELM.moving_average([1.0]) == [1.0] @test CausalELM.moving_average([1.0, 2.0, 3.0]) == [1.0, 1.5, 2.0] end end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
4940
using Test using CausalELM x, t, y = rand(100, 5), [rand() < 0.4 for i in 1:100], Float64.([rand() < 0.4 for i in 1:100]) g_computer = GComputation(x, t, y) estimate_causal_effect!(g_computer) g_inference = CausalELM.generate_null_distribution(g_computer, 10) p1, stderr1 = CausalELM.quantities_of_interest(g_computer, 10) summary1 = summarize(g_computer, n=10, inference=true) dm = DoubleMachineLearning(x, 5 * randn(100) .+ 2, y) estimate_causal_effect!(dm) dm_inference = CausalELM.generate_null_distribution(dm, 10) p2, stderr2 = CausalELM.quantities_of_interest(dm, 10) summary2 = summarize(dm, n=10) # With a continuous treatment variable dm_continuous = DoubleMachineLearning(x, t, rand(1:4, 100)) estimate_causal_effect!(dm_continuous) dm_continuous_inference = CausalELM.generate_null_distribution(dm_continuous, 10) p3, stderr3 = CausalELM.quantities_of_interest(dm_continuous, 10) summary3 = summarize(dm_continuous, n=10) x₀, y₀, x₁, y₁ = rand(1:100, 100, 5), rand(100), rand(10, 5), rand(10) its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) estimate_causal_effect!(its) summary4 = summarize(its, n=10) summary4_inference = summarize(its, n=10, inference=true) # Null distributions for the mean and cummulative changes its_inference1 = CausalELM.generate_null_distribution(its, 10, true) its_inference2 = CausalELM.generate_null_distribution(its, 10, false) p4, stderr4 = CausalELM.quantities_of_interest(its, 10, true) slearner = SLearner(x, t, y) estimate_causal_effect!(slearner) summary5 = summarize(slearner, n=10) tlearner = TLearner(x, t, y) estimate_causal_effect!(tlearner) tlearner_inference = CausalELM.generate_null_distribution(tlearner, 10) p6, stderr6 = CausalELM.quantities_of_interest(tlearner, 10) summary6 = summarize(tlearner, n=10) xlearner = XLearner(x, t, y) estimate_causal_effect!(xlearner) xlearner_inference = CausalELM.generate_null_distribution(xlearner, 10) p7, stderr7 = CausalELM.quantities_of_interest(xlearner, 10) summary7 = summarize(xlearner, n=10) summary8 = summarise(xlearner, n=10) rlearner = RLearner(x, t, y) estimate_causal_effect!(rlearner) summary9 = summarize(rlearner, n=10) dr_learner = DoublyRobustLearner(x, t, y) estimate_causal_effect!(dr_learner) dr_learner_inference = CausalELM.generate_null_distribution(dr_learner, 10) p8, stderr8 = CausalELM.quantities_of_interest(dr_learner, 10) summary10 = summarize(dr_learner, n=10) @testset "Generating Null Distributions" begin @test size(g_inference, 1) === 10 @test g_inference isa Array{Float64} @test size(dm_inference, 1) === 10 @test dm_inference isa Array{Float64} @test size(dm_continuous_inference, 1) === 10 @test dm_continuous_inference isa Array{Float64} @test size(its_inference1, 1) === 10 @test its_inference1 isa Array{Float64} @test size(its_inference2, 1) === 10 @test its_inference2 isa Array{Float64} @test size(tlearner_inference, 1) === 10 @test tlearner_inference isa Array{Float64} @test size(xlearner_inference, 1) === 10 @test xlearner_inference isa Array{Float64} @test size(dr_learner_inference, 1) === 10 @test dr_learner_inference isa Array{Float64} end @testset "P-values and Standard Errors" begin @test 1 >= p1 >= 0 @test stderr1 > 0 @test 1 >= p2 >= 0 @test stderr2 > 0 @test 1 >= p3 >= 0 @test stderr3 > 0 @test 1 >= p4 >= 0 @test stderr4 > 0 @test 1 >= p6 >= 0 @test stderr6 > 0 @test 1 >= p7 >= 0 @test stderr7 > 0 @test 1 >= p8 >= 0 @test stderr8 > 0 end @testset "Full Summaries" begin # G-Computation for (k, v) in summary1 @test !isnothing(v) end # Double Machine Learning for (k, v) in summary2 @test !isnothing(v) end # Double Machine Learning with continuous treatment for (k, v) in summary3 @test !isnothing(v) end # Interrupted Time Series for (k, v) in summary4 @test !isnothing(v) end # Interrupted Time Series with randomization inference @test summary4_inference["Standard Error"] !== NaN @test summary4_inference["p-value"] !== NaN # S-Learners for (k, v) in summary5 @test !isnothing(v) end # T-Learners for (k, v) in summary6 @test !isnothing(v) end # X-Learners for (k, v) in summary7 @test !isnothing(v) end # Testing the British spelling of summarise for (k, v) in summary8 @test !isnothing(v) end # R-Learners for (k, v) in summary9 @test !isnothing(v) end # Doubly robust learner for (k, v) in summary10 @test !isnothing(v) end end @testset "Error Handling" begin @test_throws ErrorException summarize(InterruptedTimeSeries(x₀, y₀, x₁, y₁), n=10) @test_throws ErrorException summarize(GComputation(x, y, t)) @test_throws ErrorException summarize(TLearner(x, y, t)) end @test CausalELM.mean([1, 2, 3]) == 2
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
6250
using CausalELM using Test using DataFrames include("../src/models.jl") x, t, y = rand(100, 5), Float64.([rand() < 0.4 for i in 1:100]), vec(rand(1:100, 100, 1)) slearner1 = SLearner(x, t, y) estimate_causal_effect!(slearner1) # S-learner with a binary outcome s_learner_binary = SLearner(x, y, t) estimate_causal_effect!(s_learner_binary) # S-learner initialized with DataFrames x_df = DataFrame(; x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100)) t_df, y_df = DataFrame(; t=rand(0:1, 100)), DataFrame(; y=rand(100)) s_learner_df = SLearner(x_df, t_df, y_df) tlearner1 = TLearner(x, t, y) estimate_causal_effect!(tlearner1) # T-learner initialized with DataFrames t_learner_df = TLearner(x_df, t_df, y_df) # Testing with a binary outcome t_learner_binary = TLearner(x, t, Float64.([rand() < 0.8 for i in 1:100])) estimate_causal_effect!(t_learner_binary) xlearner1 = XLearner(x, t, y) xlearner1.num_neurons = 5 CausalELM.stage1!(xlearner1) stage21 = CausalELM.stage2!(xlearner1) xlearner2 = XLearner(x, t, y) xlearner2.num_neurons = 5 CausalELM.stage1!(xlearner2); CausalELM.stage2!(xlearner2); stage22 = CausalELM.stage2!(xlearner1) xlearner3 = XLearner(x, t, y) estimate_causal_effect!(xlearner3) # Testing initialization with DataFrames x_learner_df = XLearner(x_df, t_df, y_df) # Testing with binary outcome x_learner_binary = XLearner(x, t, Float64.([rand() < 0.4 for i in 1:100])) estimate_causal_effect!(x_learner_binary) rlearner = RLearner(x, t, y) estimate_causal_effect!(rlearner) # Testing initialization with DataFrames r_learner_df = RLearner(x_df, t_df, y_df) # Doubly Robust Estimation dr_learner = DoublyRobustLearner(x, t, y) X, T, Y = CausalELM.generate_folds( dr_learner.X, dr_learner.T, dr_learner.Y, dr_learner.folds ) τ̂ = CausalELM.doubly_robust_formula!(dr_learner, X, T, Y) estimate_causal_effect!(dr_learner) # Testing Doubly Robust Estimation with a binary outcome dr_learner_binary = DoublyRobustLearner(x, t, Float64.([rand() < 0.8 for i in 1:100])) estimate_causal_effect!(dr_learner_binary) # Doubly robust estimation with DataFrames dr_learner_df = DoublyRobustLearner(x_df, t_df, y_df) estimate_causal_effect!(dr_learner_df) @testset "S-Learners" begin @testset "S-Learner Structure" begin @test slearner1.X isa Array{Float64} @test slearner1.T isa Array{Float64} @test slearner1.Y isa Array{Float64} @test s_learner_df.X isa Array{Float64} @test s_learner_df.T isa Array{Float64} @test s_learner_df.Y isa Array{Float64} end @testset "S-Learner Estimation" begin @test isa(slearner1.causal_effect, Array{Float64}) @test isa(s_learner_binary.causal_effect, Array{Float64}) end end @testset "T-Learners" begin @testset "T-Learner Structure" begin @test tlearner1.X !== Nothing @test tlearner1.T !== Nothing @test tlearner1.Y !== Nothing @test t_learner_df.X !== Nothing @test t_learner_df.T !== Nothing @test t_learner_df.Y !== Nothing end @testset "T-Learner Estimation" begin @test isa(tlearner1.causal_effect, Array{Float64}) @test isa(t_learner_binary.causal_effect, Array{Float64}) end end @testset "X-Learners" begin @testset "First Stage X-Learner" begin @test typeof(xlearner1.μ₀) <: CausalELM.ELMEnsemble @test typeof(xlearner1.μ₁) <: CausalELM.ELMEnsemble @test xlearner1.ps isa Array{Float64} @test typeof(xlearner2.μ₀) <: CausalELM.ELMEnsemble @test typeof(xlearner2.μ₁) <: CausalELM.ELMEnsemble @test xlearner2.ps isa Array{Float64} end @testset "Second Stage X-Learner" begin @test length(stage21) == 2 @test eltype(stage21) <: CausalELM.ELMEnsemble @test length(stage22) == 2 @test eltype(stage22) <: CausalELM.ELMEnsemble end @testset "X-Learner Structure" begin @test xlearner3.X !== Nothing @test xlearner3.T !== Nothing @test xlearner3.Y !== Nothing @test x_learner_df.X !== Nothing @test x_learner_df.T !== Nothing @test x_learner_df.Y !== Nothing end @testset "X-Learner Estimation" begin @test typeof(xlearner3.μ₀) <: CausalELM.ELMEnsemble @test typeof(xlearner3.μ₁) <: CausalELM.ELMEnsemble @test xlearner3.ps isa Array{Float64} @test xlearner3.causal_effect isa Array{Float64} @test x_learner_binary.causal_effect isa Array{Float64} end end @testset "R-learning" begin @testset "R-learner Structure" begin @test rlearner.X isa Array{Float64} @test rlearner.T isa Array{Float64} @test rlearner.Y isa Array{Float64} @test r_learner_df.X isa Array{Float64} @test r_learner_df.T isa Array{Float64} @test r_learner_df.Y isa Array{Float64} end @testset "R-learner estimation" begin @test rlearner.causal_effect isa Vector @test length(rlearner.causal_effect) == length(y) @test eltype(rlearner.causal_effect) == Float64 @test all(isnan, rlearner.causal_effect) == false end end @testset "Doubly Robust Learners" begin @testset "Doubly Robust Learner Structure" begin for field in fieldnames(typeof(dr_learner)) @test getfield(dr_learner, field) !== Nothing end for field in fieldnames(typeof(dr_learner_df)) @test getfield(dr_learner_df, field) !== Nothing end end @testset "Calling estimate_effect!" begin @test length(τ̂) === length(dr_learner.Y) end @testset "Doubly Robust Learner Estimation" begin @test dr_learner.causal_effect isa Vector @test length(dr_learner.causal_effect) === length(y) @test eltype(dr_learner.causal_effect) == Float64 @test all(isnan, dr_learner.causal_effect) == false @test dr_learner_df.causal_effect isa Vector @test length(dr_learner_df.causal_effect) === length(y) @test eltype(dr_learner_df.causal_effect) == Float64 @test dr_learner_binary.causal_effect isa Vector @test length(dr_learner_binary.causal_effect) === length(y) @test eltype(dr_learner_binary.causal_effect) == Float64 end end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
2438
using Test using CausalELM length4, length5 = rand(4), rand(5) @testset "Mean squared error" begin @test mse([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]) == 0 @test mse([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]) == 4 @test mse([1.0, 1.0, 1.0], [2.0, 2.0, 2.0]) == 1 end @testset "Mean absolute error" begin @test mae([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]) == 0 @test mae([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]) == 2 @test mae([1.0, 1.0, 1.0], [2.0, 2.0, 2.0]) == 1 end @testset "Confusion Matrix" begin @test CausalELM.confusion_matrix([1, 1, 1, 1, 0], [1, 1, 1, 1, 0]) == [1 0; 0 4] @test CausalELM.confusion_matrix([1, 0, 1, 0], [0, 1, 0, 1]) == [0 2; 2 0] @test CausalELM.confusion_matrix([1, 1, 1, 1, 0, 2], [1, 1, 1, 1, 0, 2]) == [ 1 0 0 0 4 0 0 0 1 ] @test CausalELM.confusion_matrix(rand(0:1, 5, 3), rand(0:1, 5, 3)) isa Matrix end @testset "Accuracy" begin @test accuracy([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]) == 0 @test accuracy([1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]) == 1 @test accuracy([1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 0.0]) == 0.5 @test accuracy([1.0, 2.0, 3.0, 4.0], [1.0, 1.0, 1.0, 1.0]) == 0.25 # Testing with one hot encoding for multiclass classification @test accuracy( [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0], [0.0 0.0 1.0; 0.0 1.0 0.0; 1.0 0.0 0.0] ) ≈ 0.33333333333 end @testset "Precision" begin @test CausalELM.precision([0, 1, 0, 0], [0, 1, 1, 0]) == 1.0 @test CausalELM.precision([0, 1, 0, 0], [0, 1, 0, 0]) == 1.0 @test CausalELM.precision([1, 2, 1, 3, 0], [2, 2, 2, 3, 1]) ≈ 0.333333333 @test CausalELM.precision([1, 2, 1, 3, 2], [2, 2, 2, 3, 1]) ≈ 0.444444444 end @testset "Recall" begin @test recall([0, 1, 0, 0], [0, 1, 1, 0]) == 0.6666666666666666 @test recall([0, 1, 0, 0], [0, 1, 0, 0]) == 1 @test recall([1, 2, 1, 3, 0], [2, 2, 2, 3, 1]) == 0.5 @test recall([1, 2, 1, 3, 2], [2, 2, 2, 3, 1]) == 0.5 end @testset "F1 Score" begin @test F1([0, 1, 0, 0], [0, 1, 1, 0]) == 0.8 @test F1([0, 1, 0, 0], [0, 1, 0, 0]) == 1 @test F1([1, 2, 1, 3, 0], [2, 2, 2, 3, 1]) == 0.4 @test F1([1, 2, 1, 3, 2], [2, 2, 2, 3, 1]) == 0.47058823529411764 end @testset "Dimension Mismatch" begin @test_throws DimensionMismatch mse(length4, length5) @test_throws DimensionMismatch mae(length4, length5) @test_throws DimensionMismatch accuracy(length4, length5) end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
9781
using Test using CausalELM x₀, y₀, x₁, y₁ = Float64.(rand(1:5, 100, 5)), randn(100), rand(1:5, (10, 5)), randn(10) its = InterruptedTimeSeries(x₀, y₀, x₁, y₁) estimate_causal_effect!(its) its_independence = CausalELM.covariate_independence(its) wald_test = CausalELM.sup_wald(its) ovb = CausalELM.omitted_predictor(its) its_validation = validate(its) x, t, y = rand(100, 5), Float64.([rand() < 0.4 for i in 1:100]), vec(rand(1:100, 100, 1)) g_computer = GComputation(x, t, y; temporal=false) estimate_causal_effect!(g_computer) test_outcomes = g_computer.Y[g_computer.T .== 1] # Create binary GComputation to test E-values with a binary outcome x1, y1 = rand(100, 5), Float64.([rand() < 0.4 for i in 1:100]) t1 = Float64.([rand() < 0.4 for i in 1:100]) binary_g_computer = GComputation(x1, t1, y1; temporal=false) estimate_causal_effect!(binary_g_computer) # Create binary GComputation to test E-values with a count outcome x2, y2 = rand(100, 5), rand(1.0:5.0, 100) t2 = Float64.([rand() < 0.4 for i in 1:100]) count_g_computer = GComputation(x2, t2, y2; temporal=false) estimate_causal_effect!(count_g_computer) continuous_counterfactual_violations = CausalELM.simulate_counterfactual_violations( randn(100), 0.25 ) discrete_counterfactual_violations = CausalELM.simulate_counterfactual_violations( rand(1:5, 100), 0.05 ) # Create double machine learning estimator dml = DoubleMachineLearning(x, t, y) estimate_causal_effect!(dml) # Testing the risk ratio with a nonbinary treatment variable nonbinary_dml = DoubleMachineLearning(x, rand(1:3, 100), y) estimate_causal_effect!(nonbinary_dml) # Testing the risk ratio with a nonbinary treatment variable and nonbinary outcome nonbinary_dml_y = DoubleMachineLearning(x, rand(1:3, 100), rand(100)) estimate_causal_effect!(nonbinary_dml_y) # Initialize an S-learner s_learner = SLearner(x, t, y) estimate_causal_effect!(s_learner) # Initialize a binary S-learner s_learner_binary = SLearner(x, t1, y1) estimate_causal_effect!(s_learner_binary) # Use with a continuous outcome to test validate s_learner_continuous = SLearner(x, t, 5 * randn(100) .+ 2) estimate_causal_effect!(s_learner_continuous) # Initialize a binary T-learner t_learner_binary = TLearner(x, t1, y1) estimate_causal_effect!(t_learner_binary) # Initialize a T-learner t_learner = TLearner(x, t, y) estimate_causal_effect!(t_learner) # Initialize an X-learner x_learner = XLearner(x, t, y) estimate_causal_effect!(x_learner) # Create an R-learner r_learner = RLearner(x, t, y) estimate_causal_effect!(r_learner) # Used to test ErrorException r_learner_no_effect = RLearner(x, t, y) # Doubly robust leaner for testing dr_learner = DoublyRobustLearner(x, t, y) estimate_causal_effect!(dr_learner) @testset "Variable Types and Conversion" begin @testset "Variable Types" begin @test CausalELM.var_type([0, 1, 0, 1, 1]) isa CausalELM.Binary @test CausalELM.var_type([1, 2, 3]) isa CausalELM.Count @test CausalELM.var_type([1.1, 2.2, 3]) isa CausalELM.Continuous end @testset "Binarization" begin @test CausalELM.binarize([1, 0], 2) == [1, 0] @test CausalELM.binarize([1, 2, 3, 4], 2) == [0, 0, 1, 1] end end @testset "p-values" begin @testset "p-values for OLS" begin @test 0 <= CausalELM.p_val( reduce(hcat, (float(rand(0:1, 10)), ones(10))), rand(10), 0.5 ) <= 1 @test 0 <= CausalELM.p_val( reduce(hcat, (float(rand(0:1, 10)), ones(10))), rand(10), 0.5; n=100 ) <= 1 @test 0 <= CausalELM.p_val( reduce(hcat, (reduce(vcat, (zeros(5), ones(5))), ones(10))), randn(10), 0.5 ) <= 1 @test 0 <= CausalELM.p_val(randn(10, 5), rand(10), 0.5) <=1 end end @testset "Interrupted Time Series Assumptions" begin @testset "Covariate Independence Assumption" begin # Test covariate_independence method @test length(its_independence) === 6 @test all(0 .<= values(its_independence) .<= 1) === true end @testset "Wald Supremeum Test for Alternative Change Point" begin # Test sup_wald method @test wald_test isa Dict{String,Real} @test wald_test["Hypothesized Break Point"] === size(x₀, 1) @test wald_test["Predicted Break Point"] > 0 @test wald_test["Wald Statistic"] >= 0 @test 0 <= wald_test["p-value"] <= 1 end @testset "Sensitivity to Omitted Predictors" begin # Test omittedvariable method # The first test should throw an error since estimatecausaleffect! was not called @test_throws ErrorException CausalELM.omitted_predictor( InterruptedTimeSeries(x₀, y₀, x₁, y₁) ) @test ovb isa Dict{String, Float64} @test isa.(values(ovb), Float64) == Bool[1, 1, 1, 1] end @testset "All Three Assumptions" begin # All assumptions at once @test its_validation isa Tuple @test length(its_validation) === 3 end end @testset "E-values" begin @testset "Generating E-values" begin @test CausalELM.e_value(binary_g_computer) isa Real @test CausalELM.e_value(count_g_computer) isa Real @test CausalELM.e_value(g_computer) isa Real @test CausalELM.e_value(dml) isa Real @test CausalELM.e_value(t_learner) isa Real @test CausalELM.e_value(x_learner) isa Real @test CausalELM.e_value(dr_learner) isa Real end end @testset "G-Computation Assumptions" begin @testset "Counterfactual Consistency" begin @test CausalELM.counterfactual_consistency( g_computer, (0.25, 0.5, 0.75, 1.0), 10 ) isa Dict{String,Float64} end @testset "Exchangeability" begin @test CausalELM.exchangeability(binary_g_computer) isa Real @test CausalELM.exchangeability(count_g_computer) isa Real @test CausalELM.exchangeability(g_computer) isa Real end @testset "Positivity" begin @test continuous_counterfactual_violations isa Vector{<:Real} @test discrete_counterfactual_violations isa Vector{<:Real} @test minimum(discrete_counterfactual_violations) >= 1 @test maximum(discrete_counterfactual_violations) <= 5 @test size(CausalELM.positivity(binary_g_computer), 2) == size(binary_g_computer.X, 2) + 1 @test size(CausalELM.positivity(count_g_computer), 2) == size(count_g_computer.X, 2) + 1 @test size(CausalELM.positivity(g_computer), 2) == size(g_computer.X, 2) + 1 end @testset "All Assumptions for G-computation" begin @test length(validate(binary_g_computer)) == 3 @test length(validate(count_g_computer)) == 3 @test length(validate(g_computer)) == 3 end end @testset "Double Machine Learning Assumptions" begin @test CausalELM.counterfactual_consistency(dml, (0.25, 0.5, 0.75, 1.0), 10) isa Dict{String, Float64} @test CausalELM.exchangeability(dml) isa Real @test size(CausalELM.positivity(dml), 2) == size(dml.X, 2) + 1 @test length(validate(dml)) == 3 end @testset "Metalearner Assumptions" begin @testset "Counterfactual Consistency" begin @test CausalELM.counterfactual_consistency( s_learner, (0.25, 0.5, 0.75, 1.0), 10 ) isa Dict{String, Float64} @test CausalELM.counterfactual_consistency( t_learner, (0.25, 0.5, 0.75, 1.0), 10 ) isa Dict{String, Float64} @test CausalELM.counterfactual_consistency( x_learner, (0.25, 0.5, 0.75, 1.0), 10 ) isa Dict{String, Float64} @test CausalELM.counterfactual_consistency( dr_learner, (0.25, 0.5, 0.75, 1.0), 10 ) isa Dict{String, Float64} end @testset "Exchangeability" begin @test CausalELM.exchangeability(s_learner) isa Real @test CausalELM.exchangeability(t_learner) isa Real @test CausalELM.exchangeability(t_learner_binary) isa Real @test CausalELM.exchangeability(x_learner) isa Real @test CausalELM.exchangeability(nonbinary_dml) isa Real @test CausalELM.exchangeability(nonbinary_dml_y) isa Real @test CausalELM.exchangeability(dr_learner) isa Real end @testset "Positivity" begin @test size(CausalELM.positivity(s_learner), 2) == size(s_learner.X, 2) + 1 @test size(CausalELM.positivity(t_learner), 2) == size(t_learner.X, 2) + 1 @test size(CausalELM.positivity(x_learner), 2) == size(x_learner.X, 2) + 1 @test size(CausalELM.positivity(dr_learner), 2) == size(dr_learner.X, 2) + 1 end @testset "All three assumptions" begin @test length(validate(s_learner)) == 3 @test length(validate(s_learner_continuous)) === 3 @test length(validate(t_learner)) == 3 @test length(validate(x_learner)) == 3 # Only need this test because it it just passing the internal DML to the method that # was already tested @test length(validate(r_learner)) == 3 @test length(validate(dr_learner)) == 3 end end @testset "Calling validate before estimate_causal_effect!" begin @test_throws ErrorException validate(InterruptedTimeSeries(x₀, y₀, x₁, y₁)) @test_throws ErrorException validate(GComputation(x, t, y)) @test_throws ErrorException validate(DoubleMachineLearning(x, t, y)) @test_throws ErrorException validate(SLearner(x, t, y)) @test_throws ErrorException validate(TLearner(x, t, y)) @test_throws ErrorException validate(XLearner(x, t, y)) @test_throws ErrorException validate(r_learner_no_effect) @test_throws ErrorException validate(DoublyRobustLearner(x, t, y)) end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
3248
using Test using CausalELM include("../src/models.jl") # Test classification functionality using a simple XOR test borrowed from # ExtremeLearning.jl x = [1.0 1.0; 0.0 1.0; 0.0 0.0; 1.0 0.0] y = [0.0, 1.0, 0.0, 1.0] x_test = [1.0 1.0; 0.0 1.0; 0.0 0.0] big_x, big_y = rand(10000, 7), rand(10000) x1 = rand(20, 5) y1 = rand(20) x1test = rand(30, 5) mock_model = ExtremeLearner(x, y, 10, σ) m1 = ExtremeLearner(x, y, 10, σ) f1 = fit!(m1) predictions1 = predict(m1, x_test) predict_counterfactual!(m1, x_test) placebo1 = placebo_test(m1) m3 = ExtremeLearner(x1, y1, 10, σ) fit!(m3) predictions3 = predict(m3, x1test) m4 = ExtremeLearner(rand(100, 5), rand(100), 5, relu) fit!(m4) nofit = ExtremeLearner(x1, y1, 10, σ) set_weights_biases(nofit) ensemble = ELMEnsemble(big_x, big_y, 10000, 100, 5, 10, relu) fit!(ensemble) predictions = predict(ensemble, big_x) @testset "Extreme Learning Machines" begin @testset "Extreme Learning Machine Structure" begin @test mock_model.X isa Array{Float64} @test mock_model.Y isa Array{Float64} @test mock_model.training_samples == size(x, 1) @test mock_model.hidden_neurons == 10 @test mock_model.activation == σ @test mock_model.__fit == false end @testset "Model Fit" begin @test length(m1.β) == 10 @test size(m1.weights) == (2, 10) @test length(m4.β) == size(m4.X, 2) end @testset "Model Predictions" begin @test predictions1[1] < 0.1 @test predictions1[2] > 0.9 @test predictions1[3] < 0.1 # Ensure the counterfactual attribute gets step @test m1.counterfactual == predictions1 # Ensure we can predict with a test set with more data points than the training set @test isa(predictions3, Array{Float64}) end @testset "Placebo Test" begin @test length(placebo1) == 2 end @testset "Predict Before Fit" begin @test isdefined(nofit, :H) == true @test_throws ErrorException predict(nofit, x1test) @test_throws ErrorException placebo_test(nofit) end @testset "Print Models" begin msg1, msg2 = "Extreme Learning Machine with ", "hidden neurons" msg3 = "Regularized " * msg1 @test sprint(print, m1) === msg1 * string(m1.hidden_neurons) * " " * msg2 end end @testset "Extreme Learning Machine Ensembles" begin @testset "Initializing Ensembles" begin @test ensemble isa ELMEnsemble @test ensemble.X isa Array{Float64} @test ensemble.Y isa Array{Float64} @test ensemble.elms isa Array{ExtremeLearner} @test length(ensemble.elms) == 100 @test ensemble.feat_indices isa Vector{Vector{Int64}} @test length(ensemble.feat_indices) == 100 end @testset "Ensemble Fitting and Prediction" begin @test all([elm.__fit for elm in ensemble.elms]) == true @test predictions isa Vector{Float64} @test length(predictions) == 10000 end @testset "Print Models" begin msg1, msg2 = "Extreme Learning Machine Ensemble with ", "learners" msg3 = "Regularized " * msg1 @test sprint(print, ensemble) === msg1 * string(length(ensemble.elms)) * " " * msg2 end end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
code
3521
using Test using CausalELM # Variables for checking the output of the model_config macro because it is difficult model_config_avg_expr = @macroexpand CausalELM.@model_config average_effect model_config_ind_expr = @macroexpand CausalELM.@model_config individual_effect model_config_avg_idx = Int64.(collect(range(2, 18, 9))) model_config_ind_idx = Int64.(collect(range(2, 18, 9))) model_config_avg_ground_truth = quote quantity_of_interest::String temporal::Bool task::String activation::Function sample_size::Integer num_machines::Integer num_feats::Integer num_neurons::Int64 causal_effect::Float64 end model_config_ind_ground_truth = quote quantity_of_interest::String temporal::Bool task::String regularized::Bool activation::Function sample_size::Integer num_machines::Integer num_feats::Integer num_neurons::Int64 causal_effect::Array{Float64} end # Fields for the user supplied data standard_input_expr = @macroexpand CausalELM.@standard_input_data standard_input_idx = [2, 4, 6] standard_input_ground_truth = quote X::Array{Float64} T::Array{Float64} Y::Array{Float64} end # Fields for the user supplied data double_model_input_expr = @macroexpand CausalELM.@standard_input_data double_model_input_idx = [2, 4, 6] double_model_input_ground_truth = quote X::Array{Float64} T::Array{Float64} Y::Array{Float64} W::Array{Float64} end # Generating folds big_x, big_t, big_y = rand(10000, 8), rand(0:1, 10000), vec(rand(1:100, 10000, 1)) dm = DoubleMachineLearning(big_x, big_t, big_y) estimate_causal_effect!(dm) x_fold, t_fold, y_fold = CausalELM.generate_folds(dm.X, dm.T, dm.Y, dm.folds) @testset "Moments" begin @test mean([1, 2, 3]) == 2 @test CausalELM.var([1, 2, 3]) == 1 end @testset "One Hot Encoding" begin @test CausalELM.one_hot_encode([1, 2, 3]) == [1 0 0; 0 1 0; 0 0 1] end @testset "Clipping" begin @test CausalELM.clip_if_binary([1.2, -0.02], CausalELM.Binary()) == [1.0, 0.0] @test CausalELM.clip_if_binary([1.2, -0.02], CausalELM.Count()) == [1.2, -0.02] end @testset "Generating Fields with Macros" begin @test model_config_avg_ground_truth.head == model_config_avg_expr.head @test model_config_ind_ground_truth.head == model_config_ind_expr.head # We only look at even indices because the odd indices have information about what linear # of VSCode each variable was defined in, which will differ in both expressions @test ( model_config_avg_ground_truth.args[model_config_avg_idx] == model_config_avg_ground_truth.args[model_config_avg_idx] ) @test ( model_config_ind_ground_truth.args[model_config_avg_idx] == model_config_ind_ground_truth.args[model_config_avg_idx] ) @test_throws ArgumentError @macroexpand CausalELM.@model_config mean @test standard_input_expr.head == standard_input_ground_truth.head @test ( standard_input_expr.args[standard_input_idx] == standard_input_ground_truth.args[standard_input_idx] ) @test double_model_input_expr.head == double_model_input_ground_truth.head @test ( double_model_input_expr.args[double_model_input_idx] == double_model_input_ground_truth.args[double_model_input_idx] ) end @testset "Generating Folds" begin @test size(x_fold[1], 2) == size(dm.X, 2) @test y_fold isa Vector{Vector{Float64}} @test t_fold isa Vector{Vector{Float64}} @test length(t_fold) == dm.folds end
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
7057
<div align="center"> <img src="https://github.com/dscolby/dscolby.github.io/blob/main/github_logo.jpg"> </div> <p align="center"> <a href="https://github.com/dscolby/CausalELM.jl/actions"> <img src="https://github.com/dscolby/CausalELM.jl/actions/workflows/CI.yml/badge.svg?branch=main" alt="Build Status"> </a> <a href="https://app.codecov.io/gh/dscolby/CausalELM.jl/tree/main/src"> <img src="https://codecov.io/gh/dscolby/CausalELM.jl/graph/badge.svg" alt="Code Coverage"> </a> <a href="https://opensource.org/licenses/MIT"> <img src="https://img.shields.io/badge/License-MIT-yelllow" alt="License"> </a> <a href="https://dscolby.github.io/CausalELM.jl/stable"> <img src="https://img.shields.io/badge/docs-stable-blue.svg" alt="Documentation"> </a> <a href="https://dscolby.github.io/CausalELM.jl/dev/"> <img src="https://img.shields.io/badge/docs-dev-blue.svg" alt="Develmopmental Documentation"> </a> <a href="https://github.com/JuliaTesting/Aqua.jl"> <img src="https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg" alt="Aqua QA"> </a> <a href="https://github.com/JuliaDiff/BlueStyle"> <img src="https://img.shields.io/badge/code%20style-blue-4495d1.svg" alt="Code Style: Blue"> </a> </p> <p> CausalELM enables estimation of causal effects in settings where a randomized control trial or traditional statistical models would be infeasible or unacceptable. It enables estimation of the average treatment effect (ATE)/intent to treat effect (ITE) with interrupted time series analysis, G-computation, and double machine learning; average treatment effect on the treated (ATT) with G-computation; cumulative treatment effect with interrupted time series analysis; and the conditional average treatment effect (CATE) via S-learning, T-learning, X-learning, R-learning, and doubly robust estimation. Underlying all of these estimators are ensembles of extreme learning machines, a simple neural network that uses randomized weights and least squares optimization instead of gradient descent. Once a model has been estimated, CausalELM can summarize the model and conduct sensitivity analysis to validate the plausibility of modeling assumptions. Furthermore, all of this can be done in four lines of code. </p> <h2>Extreme Learning Machines and Causal Inference</h2> <p> In some cases we would like to know the causal effect of some intervention but we do not have the counterfactual, making conventional methods of statistical analysis infeasible. However, it may still be possible to get an unbiased estimate of the causal effect (ATE, ATE, or ITT) by predicting the counterfactual and comparing it to the observed outcomes. This is the approach CausalELM takes to conduct interrupted time series analysis, G-Computation, double machine learning, and metalearning via S-Learners, T-Learners, X-Learners, R-learners, and doubly robust estimation. In interrupted time series analysis, we want to estimate the effect of some intervention on the outcome of a single unit that we observe during multiple time periods. For example, we might want to know how the announcement of a merger affected the price of Stock A. To do this, we need to know what the price of stock A would have been if the merger had not been announced, which we can predict with machine learning methods. Then, we can compare this predicted counterfactual to the observed price data to estimate the effect of the merger announcement. In another case, we might want to know the effect of medicine X on disease Y but the administration of X was not random and it might have also been administered at mulitiple time periods, which would produce biased estimates. To overcome this, G-computation models the observed data, uses the model to predict the outcomes if all patients recieved the treatment, and compares it to the predictions of the outcomes if none of the patients recieved the treatment. Double machine learning (DML) takes a similar approach but also models the treatment mechanism and uses it to adjust the initial estimates. This approach has three advantages. First, it is more efficient with high dimensional data than conventional methods. Metalearners take a similar approach to estimate the CATE. While all of these models are different, they have one thing in common: how well they perform depends on the underlying model they fit to the data. To that end, CausalELMs use bagged ensembles of extreme learning machines because they are simple yet flexible enough to be universal function approximators with lower varaince than single extreme learning machines. </p> <h2>CausalELM Features</h2> <ul> <li>Estimate a causal effect, get a summary, and validate assumptions in just four lines of code</li> <li>Bagging improves performance and reduces variance without the need to tune a regularization parameter</li> <li>Enables using the same structs for regression and classification</li> <li>Includes 13 activation functions and allows user-defined activation functions</li> <li>Most inference and validation tests do not assume functional or distributional forms</li> <li>Implements the latest techniques form statistics, econometrics, and biostatistics</li> <li>Works out of the box with arrays or any data structure that implements the Tables.jl interface</li> <li>Codebase is high-quality, well tested, and regularly updated</li> </ul> <h2>What's New?</h2> <ul> <li>Now includes doubly robust estimator for CATE estimation</li> <li>All estimators now implement bagging to reduce predictive performance and reduce variance</li> <li>Counterfactual consistency validation simulates more realistic violations of the counterfactual consistency assumption</li> <li>Uses a simple heuristic to choose the number of neurons, which reduces training time and still works well in practice</li> <li>Probability clipping for classifier predictions and residuals is no longer necessary due to the bagging procedure</li> <li>CausalELM talk has been accepted to JuliaCon 2024!</li> </ul> <h2>What's Next?</h2> <p> Newer versions of CausalELM will hopefully support using GPUs and provide interpretations of the results of calling validate on a model that has been estimated. In addition, some estimators will also support using instrumental variables. However, these priorities could also change depending on feedback recieved at JuliaCon. </p> <h2>Disclaimer</h2> CausalELM is extensively tested and almost every function or method has multiple tests. That being said, CausalELM is still in the early/ish stages of development and may have some bugs. Also, expect breaking releases for now. <h2>Contributing</h2> <p> All contributions are welcome. Before submitting a pull request please read the <a href="https://dscolby.github.io/CausalELM.jl/stable/contributing/">contribution guidlines. </p>
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
1691
# CausalELM ```@docs CausalELM.CausalELM ``` ## Types ```@docs InterruptedTimeSeries GComputation DoubleMachineLearning SLearner TLearner XLearner RLearner DoublyRobustLearner CausalELM.CausalEstimator CausalELM.Metalearner CausalELM.ExtremeLearner CausalELM.ELMEnsemble CausalELM.Nonbinary CausalELM.Binary CausalELM.Count CausalELM.Continuous ``` ## Activation Functions ```@docs binary_step σ CausalELM.tanh relu leaky_relu swish softmax softplus gelu gaussian hard_tanh elish fourier ``` ## Average Causal Effect Estimators ```@docs CausalELM.g_formula! CausalELM.predict_residuals CausalELM.moving_average ``` ## Metalearners ```@docs CausalELM.doubly_robust_formula! CausalELM.stage1! CausalELM.stage2! ``` ## Common Methods ```@docs estimate_causal_effect! ``` ## Inference ```@docs summarize CausalELM.generate_null_distribution CausalELM.quantities_of_interest ``` ## Model Validation ```@docs validate CausalELM.covariate_independence CausalELM.omitted_predictor CausalELM.sup_wald CausalELM.p_val CausalELM.counterfactual_consistency CausalELM.simulate_counterfactual_violations CausalELM.exchangeability CausalELM.e_value CausalELM.binarize CausalELM.risk_ratio CausalELM.positivity ``` ## Validation Metrics ```@docs mse mae accuracy CausalELM.precision recall F1 CausalELM.confusion_matrix ``` ## Extreme Learning Machines ```@docs CausalELM.fit! CausalELM.predict CausalELM.predict_counterfactual! CausalELM.placebo_test CausalELM.set_weights_biases ``` ## Utility Functions ```@docs CausalELM.var_type CausalELM.mean CausalELM.var CausalELM.one_hot_encode CausalELM.clip_if_binary CausalELM.@model_config CausalELM.@standard_input_data CausalELM.generate_folds ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
3908
# Contributing All contributions are welcome. To ensure contributions align with the existing code base and are not duplicated, please follow the guidelines below. ## Reporting a Bug To report a bug, open an issue on the CausalELM GitHub [page](https://github.com/dscolby/CausalELM.jl/issues). Please include all relevant information, such as what methods were called, the operating system used, the verion/s of causalELM used, the verion/s of Julia used, any tracebacks or error codes, and any other information that would be helpful for debugging. Also be sure to use the bug label. ## Requesting New Features Before requesting a new feature, please check the issues page on [GitHub](https://github.com/dscolby/CausalELM.jl/issues) to make sure someone else did not already request the same feature. If this is not the case, then please open an issue that explains what function or method you would like to be added and how you believe it should behave. Also be sure to use the enhancement tag. ## Contributing Code Before submitting a [pull request](https://github.com/dscolby/CausalELM.jl/pulls), please open an issue explaining what the proposed code is and why you want to add it, if there is not already an issue that addresses your changes and you are not fixing something very minor. When submitting a pull request, please reference the relevant issue/s and ensure your code follows the guidelines below. * Before being merged, all pull requests should be well tested and all tests must be passing. * All abstract types, structs, functions, methods, macros, and constants have docstrings that follow the same format as the other docstrings. These functions should also be included in the relevant section of the API Manual. * Most new structs for estimating causal effects should have mostly the same fields. To reduce the burden of repeatedly defining all these fields, it is advisable to use the model_config and standard_input_data macros to programmatically generate fields for new structs. Doing so will ensure that with little to no effort the new structs will work with the summarize and validate methods. * There are no repeated code blocks. If there are repeated codeblocks, then they should be consolidated into a separate function. * Interanl methods can contain types and be parametric but public methods should be as general as possible. * Minimize use of new constants and macros. If they must be included, the reason for their inclusion should be obvious or included in the docstring. * Avoid using global variables and constants. * Code should take advantage of Julia's built in macros for performance. Use @inbounds, @view, @fastmath, and @simd when possible. * When appending to an array in a loop, preallocate the array and update its values by index. * Avoid long functions and decompose them into smaller functions or methods. A general rule is that function definitions should fit within the screen of a laptop. * Use self-explanatory names for variables, methods, structs, constants, and macros. * Make generous use of whitespace. * All functions should include docstrings. ** Docstrings may contain arguments, keywords, notes, references, and examples sections in that order but some sections may be skipped. ** At a minimum, docstrings should contain the signature/s, a short description, and examples ** Each section should include its own level one header. !!! note CausalELM follows the Blue style guide and all code is automatically formatted to conform with this standard upon being pushed to GitHub. ## Updating or Fixing Documentation To propose a change to the documentation please submit an [issue](https://github.com/dscolby/CausalELM/issues) or [pull request](https://github.com/dscolby/CausalELM/pulls).
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
5022
```@raw html <div style="width:100%; height:15px;; border-radius:6px;text-align:center; color:#1e1e20"> <a class="github-button" href="https://github.com/dscolby/CausalELM.jl" data-icon="octicon-star" data-size="large" data-show-count="true" aria-label="Star dscolby/CausalELM.jl on GitHub" style="margin:auto">Star</a> <script async defer src="https://buttons.github.io/buttons.js"></script> </div> ``` ```@meta CurrentModule = CausalELM ``` # Overview CausalELM leverages new techniques in machine learning and statistics to estimate individual and aggregate treatment effects in situations where traditional methods are unsatisfactory or infeasible. To enable this, CausalELM provides a simple API to initialize a model, estimate a causal effect, get a summary of the model, and test its robustness. CausalELM includes estimators for interupted time series analysis, G-Computation, double machine learning, S-Learning, T-Learning, X-Learning, R-learning, and doubly robust estimation. Underlying all these estimators are bagged extreme learning machines. Extreme learning machines are a single layer feedfoward neural network that relies on randomized weights and least squares optimization, making them expressive, simple, and computationally efficient. Combining them with bagging reduces the variance caused by the randomization of weights and provides a form of regularization that does not have to be tuned through cross validation. These attributes make CausalELM a very simple and powerful package for estimating treatment effects. ### Features * Estimate a causal effect, get a summary, and validate assumptions in just four lines of code * Bagging improves performance and reduces variance without the need to tune a regularization parameter * Enables using the same structs for regression and classification * Includes 13 activation functions and allows user-defined activation functions * Most inference and validation tests do not assume functional or distributional forms * Implements the latest techniques from statistics, econometrics, and biostatistics * Works out of the box with arrays or any data structure that implements the Tables.jl interface * Codebase is high-quality, well tested, and regularly updated ### What's New? * Now includes doubly robust estimator for CATE estimation * All estimators now implement bagging to reduce predictive performance and reduce variance * Counterfactual consistency validation simulates more realistic violations of the counterfactual consistency assumption * Uses a simple heuristic to choose the number of neurons, which reduces training time and still works well in practice * Probability clipping for classifier predictions and residuals is no longer necessary due to the bagging procedure * CausalELM talk has been accepted to JuliaCon 2024! ### What makes CausalELM different? Other packages, mainly EconML, DoWhy, CausalAI, and CausalML, have similar funcitonality. Beides being written in Julia rather than Python, the main differences between CausalELM and these libraries are: * Simplicity is core to casualELM's design philosophy. CausalELM only uses one type of machine learning model, extreme learning machines (with bagging) and does not require you to import any other packages or initialize machine learning models, pass machine learning structs to CausalELM's estimators, convert dataframes or arrays to a special type, or one hot encode categorical treatments. By trading a little bit of flexibility for a simpler API, all of CausalELM's functionality can be used with just four lines of code. * As part of this design principle, CausalELM's estimators decide whether to use regression or classification based on the type of outcome variable. This is in contrast to most machine learning packages, which have separate classes or structs fro regressors and classifiers of the same model. * CausalELM's validate method, which is specific to each estimator, allows you to validate or test the sentitivity of an estimator to possible violations of identifying assumptions. * Unlike packages that do not allow you to estimate p-values and standard errors, use bootstrapping to estimate them, or use incorrect hypothesis tests, all of CausalELM's estimators provide p-values and standard errors generated via approximate randomization inference. * CausalELM strives to be lightweight while still being powerful and therefore does not have external dependencies: all the functions it uses are in the Julia standard library. * The other packages and many others mostly use techniques from one field. Instead, CausalELM incorporates a hodgepodge of ideas from statistics, machine learning, econometrics, and biostatistics. ### Installation CausalELM requires Julia version 1.7 or greater and can be installed from the REPL as shown below. ```julia using Pkg Pkg.add("CausalELM") ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
6797
# Release Notes These release notes adhere to the [keep a changelog](https://keepachangelog.com/en/1.0.0/) format. Below is a list of changes since CausalELM was first released. ## Version [v0.7.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.6.1) - 2024-06-22 ### Added * Implemented bagged ensemble of extreme learning machines to use with estimators [#67](https://github.com/dscolby/CausalELM.jl/issues/67) * Implemented multithreading for testing the sensitivity of estimators to the counterfactual consistency assumption ### Changed * Compute the number of neurons to use with log heuristic instead of cross validation [#62](https://github.com/dscolby/CausalELM.jl/issues/62) * Calculate probabilities as the average label predicted by the ensemble instead of clipping [#71](https://github.com/dscolby/CausalELM.jl/issues/71) * Made calculation of p-values and standard errors optional and not executed by default in summarize methods [#65](https://github.com/dscolby/CausalELM.jl/issues/65) * Removed redundant W argument for double machine learning, R-learning, and doubly robust estimation [#68](https://github.com/dscolby/CausalELM.jl/issues/68) * Use swish as the default activation function [#72](https://github.com/dscolby/CausalELM.jl/issues/72) * Implemented noise as a function of each observation instead of the variance of the outcome when testing the sensitivity of the counterfactual consistency assumption [#74](https://github.com/dscolby/CausalELM.jl/issues/74) * p-values and standard errors for randomization inference are generated in parallel ### Fixed * Applying the weight trick for R-learning [#70](https://github.com/dscolby/CausalELM.jl/issues/70) ## Version [v0.6.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.6.0) - 2024-06-15 ### Added * Implemented doubly robust learner for CATE estimation [#31](https://github.com/dscolby/CausalELM.jl/issues/31) * Provided better explanations of supported treatment and outcome variable types in the docs [#41](https://github.com/dscolby/CausalELM.jl/issues/41) * Added support for specifying confounders, W, separate from covariates of interest, X, for double machine learning and doubly robust estimation [39](https://github.com/dscolby/CausalELM.jl/issues/39) ### Changed * Removed the estimate_causal_effect! call in the model constructor docstrings [#35](https://github.com/dscolby/CausalELM.jl/issues/35) * Standardized and improved docstrings and added doctests [#44](https://github.com/dscolby/CausalELM.jl/issues/44) * Counterfactual consistency now simulates outcomes that violate the counterfactual consistency assumption rather than binning of treatments and works with discrete or continuous treatments [#33](https://github.com/dscolby/CausalELM.jl/issues/33) * Refactored estimator and metalearner structs, constructors, and estimate_causal_effect! methods [#45](https://github.com/dscolby/CausalELM.jl/issues/45) ### Fixed * Clipped probabilities between 0 and 1 for estimators that use predictions of binary variables [#36](https://github.com/dscolby/CausalELM.jl/issues/36) * Fixed sample splitting and cross fitting procedure for doubly robust estimation [#42](https://github.com/dscolby/CausalELM.jl/issues/42) * Addressed numerical instability when finding the ridge penalty by replacing the previous ridge formula with generalized cross validation [#43](https://github.com/dscolby/CausalELM.jl/issues/43) * Uses the correct variable in the ommited predictor test for interrupted time series. * Uses correct range for p-values in interrupted time series validation tests. * Correctly subsets the data for ATT estimation in G-computation [#52](https://github.com/dscolby/CausalELM.jl/issues/52) ## Version [v0.5.1](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.5.1) - 2024-01-15 ### Added * More descriptive docstrings [#21](https://github.com/dscolby/CausalELM.jl/issues/21) ### Fixed * Permutation of continuous treatments draws from a continuous, instead of discrete uniform distribution during randomization inference ## Version [v0.5.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.5.0) - 2024-01-13 ### Added * Constructors for estimators taht accept dataframes from DataFrames.jl [#25](https://github.com/dscolby/CausalELM.jl/issues/25) ### Changed * Estimators can handle any array whose values are <:Real [#23](https://github.com/dscolby/CausalELM.jl/issues/23) * Estimator constructors are now called with model(X, T, Y) instead of model(X, Y, T) * Removed excess type constraints for many methods [#23](https://github.com/dscolby/CausalELM.jl/issues/23) * Vectorized a few for loops * Increased test coverage ## Version [v0.4.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.4.0) - 2024-01-06 ### Added * R-learning * Softmax function for arrays ### Changed * Moved all types and methods under the main module * Decreased size of function definitions [#22](https://github.com/dscolby/CausalELM.jl/issues/15) * SLearner has a G-computation field that does the heavy lifting for S-learning * Removed excess fields from estimator structs ### Fixed * Changed the incorrect name of DoublyRobustEstimation struct to DoubleMachineLearning * Caclulation of risk ratios and E-values * Calculation of validation metrics for multiclass classification * Calculation of output weights for L2 regularized extreme learning machines ## Version [v0.3.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.3.0) - 2023-11-25 ### Added * Splitting of temporal data for cross validation [18](https://github.com/dscolby/CausalELM.jl/issues/18) * Methods to validate/test senstivity to violations of identifying assumptions [#16](https://github.com/dscolby/CausalELM.jl/issues/16) ### Changed * Converted all functions and methods to snake case [#17](https://github.com/dscolby/CausalELM.jl/issues/17) * Randomization inference for interrupted time series randomizes all the indices [#15](https://github.com/dscolby/CausalELM.jl/issues/15) ### Fixed * Issue related to recoding variables to calculate validation metrics for cross validation ## Version [v0.2.1](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.2.1) - 2023-06-07 ### Added * Cross fitting to the doubly robust estimator ## Version [v0.2.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.2.0) - 2023-04-16 ### Added * Calculation of p-values and standard errors via randomization inference ### Changed * Divided package into modules ## Version [v0.1.0](https://github.com/dscolby/CausalELM.jl/releases/tag/v0.1.0) - 2023-02-14 ### Added * Event study, g-computation, and doubly robust estimators * S-learning, T-learning, and X-learning * Model summarization methods
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
6052
# Double Machine Learning Double machine learning, also called debiased or orthogonalized machine learning, enables estimating causal effects when the dimensionality of the covariates is too high for linear regression or the treatment or outcomes cannot be easily modeled parametrically. Double machine learning estimates models of the treatment assignment and outcome and then combines them in a final model. This is a semiparametric model in the sense that the first stage models can take on any functional form but the final stage model is a linear combination of the residuals from the first stage models. !!! note For more information see: Chernozhukov, Victor, Denis Chetverikov, Mert Demirer, Esther Duflo, Christian Hansen, Whitney Newey, and James Robins. "Double/debiased machine learning for treatment and structural parameters." (2018): C1-C68. ## Step 1: Initialize a Model The DoubleMachineLearning constructor takes at least three arguments—covariates, a treatment statuses, and outcomes, all of which may be either an array or any struct that implements the Tables.jl interface (e.g. DataFrames). This estimator supports binary, count, or continuous treatments and binary, count, continuous, or time to event outcomes. !!! note Non-binary categorical outcomes are treated as continuous. !!! tip You can also specify the the number of folds to use for cross-fitting, the number of extreme learning machines to incorporate in the ensemble, the number of features to consider for each extreme learning machine, the activation function to use, the number of observations to bootstrap in each extreme learning machine, and the number of neurons in each extreme learning machine. These arguments are specified with the folds, num_machines, num_features, activation, sample_size, and num\_neurons keywords. ```julia # Create some data with a binary treatment X, T, Y, W = rand(100, 5), [rand()<0.4 for i in 1:100], rand(100), rand(100, 4) # We could also use DataFrames or any other package implementing the Tables.jl API # using DataFrames # X = DataFrame(x1=rand(100), x2=rand(100), x3=rand(100), x4=rand(100), x5=rand(100)) # T, Y = DataFrame(t=[rand()<0.4 for i in 1:100]), DataFrame(y=rand(100)) dml = DoubleMachineLearning(X, T, Y) ``` ## Step 2: Estimate the Causal Effect To estimate the causal effect, we call estimate_causal_effect! on the model above. ```julia # we could also estimate the ATT by passing quantity_of_interest="ATT" estimate_causal_effect!(dml) ``` # Get a Summary We can get a summary of the model by pasing the model to the summarize method. !!!note To calculate the p-value and standard error for the treatmetn effect, you can set the inference argument to false. However, p-values and standard errors are calculated via randomization inference, which will take a long time. But can be sped up by launching Julia with a higher number of threads. ```julia # Can also use the British spelling # summarise(dml) summarize(dml) ``` ## Step 4: Validate the Model We can validate the model by examining the plausibility that the main assumptions of causal inference, counterfactual consistency, exchangeability, and positivity, hold. It should be noted that consistency and exchangeability are not directly testable, so instead, these tests do not provide definitive evidence of a violation of these assumptions. To probe the counterfactual consistency assumption, we simulate counterfactual outcomes that are different from the observed outcomes, estimate models with the simulated counterfactual outcomes, and take the averages. If the outcome is continuous, the noise for the simulated counterfactuals is drawn from N(0, dev) for each element in devs and each outcome, multiplied by the original outcome, and added to the original outcome. For discrete variables, each outcome is replaced with a different value in the range of outcomes with probability ϵ for each ϵ in devs, otherwise the default is 0.025, 0.05, 0.075, 0.1. If the average estimate for a given level of violation differs greatly from the effect estimated on the actual data, then the model is very sensitive to violations of the counterfactual consistency assumption for that level of violation. Next, this method tests the model's sensitivity to a violation of the exchangeability assumption by calculating the E-value, which is the minimum strength of association, on the risk ratio scale, that an unobserved confounder would need to have with the treatment and outcome variable to fully explain away the estimated effect. Thus, higher E-values imply the model is more robust to a violation of the exchangeability assumption. Finally, this method tests the positivity assumption by estimating propensity scores. Rows in the matrix are levels of covariates that have a zero or near zero probability of treatment. If the matrix is empty, none of the observations have an estimated zero probability of treatment, which implies the positivity assumption is satisfied. !!! tip One can also specify the maxium number of possible treatments to consider for the causal consistency assumption and the minimum and maximum probabilities of treatment for the positivity assumption with the num\_treatments, min, and max keyword arguments. !!! danger Obtaining correct estimates is dependent on meeting the assumptions for double machine learning. If the assumptions are not met then any estimates may be biased and lead to incorrect conclusions. !!! note For a thorough review of casual inference assumptions see: Hernan, Miguel A., and James M. Robins. Causal inference what if. Boca Raton: Taylor and Francis, 2024. For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. ```julia validate(g_computer) ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
2072
# Deciding Which Estimator to Use Which model you should use depends on what you are trying to model and the type of data you have. The table below can serve as a useful reference when deciding which model to use for a given dataset and causal question. | Model | Struct | Causal Estimands | Supported Treatment Types | Supported Outcome Types | |----------------------------------|-----------------------|----------------------------------|---------------------------|------------------------------------------| | Interrupted Time Series Analysis | InterruptedTimeSeries | ATE, Cumulative Treatment Effect | Binary | Continuous, Count[^1], Time to Event | | G-computation | GComputation | ATE, ATT, ITT | Binary | Binary,Continuous, Time to Event, Count[^1] | | Double Machine Learning | DoubleMachineLearning | ATE | Binary, Count[^1], Continuous | Binary, Count[^1], Continuous, Time to Event | | S-learning | SLearner | CATE | Binary | Binary, Continuous, Time to Event, Count[^1] | | T-learning | TLearner | CATE | Binary | Binary, Continuous, Count[^1], Time to Event | | X-learning | XLearner | CATE | Binary | Binary, Continuous, Count[^1], Time to Event | | R-learning | RLearner | CATE | Binary, Count[^1], Continuous | Binary, Count[^1], Continuous, Time to Event | | Doubly Robust Estimation | DoublyRobustLearner | CATE | Binary | Binary, Continuous, Count[^1], Time to Event | [^1]: Similar to other packages, predictions of count variables is treated as a continuous regression task.
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
5996
# G-Computation In some cases, we may want to know the causal effect of a treatment that varies and is confounded over time. For example, a doctor might want to know the effect of a treatment given at multiple times whose status depends on the health of the patient at a given time. One way to get an unbiased estimate of the causal effect is to use G-computation. The basic steps for using G-computation in CausalELM are below. !!! note For a good overview of G-Computation see: Chatton, Arthur, Florent Le Borgne, Clémence Leyrat, Florence Gillaizeau, Chloé Rousseau, Laetitia Barbin, David Laplaud, Maxime Léger, Bruno Giraudeau, and Yohann Foucher. "G-computation, propensity score-based methods, and targeted maximum likelihood estimator for causal inference with different covariates sets: a comparative simulation study." Scientific reports 10, no. 1 (2020): 9219. ## Step 1: Initialize a Model The GComputation constructor takes at least three arguments: covariates, treatment statuses, outcomes, all of which can be either an array or any data structure that implements the Tables.jl interface (e.g. DataFrames). This implementation supports binary treatments and binary, continuous, time to event, and count outcome variables. !!! note Non-binary categorical outcomes are treated as continuous. !!! tip You can also specify the causal estimand, which activation function to use, whether the data is of a temporal nature, the number of extreme learning machines to use, the number of features to consider for each extreme learning machine, the number of bootstrapped observations to include in each extreme learning machine, and the number of neurons to use during estimation. These options are specified with the following keyword arguments: quantity\_of\_interest, activation, temporal, num_machines, num_feats, sample_size, and num\_neurons. ```julia # Create some data with a binary treatment X, T, Y = rand(1000, 5), [rand()<0.4 for i in 1:1000], rand(1000) # We could also use DataFrames or any other package that implements the Tables.jl API # using DataFrames # X = DataFrame(x1=rand(1000), x2=rand(1000), x3=rand(1000), x4=rand(1000), x5=rand(1000)) # T, Y = DataFrame(t=[rand()<0.4 for i in 1:1000]), DataFrame(y=rand(1000)) g_computer = GComputation(X, T, Y) ``` ## Step 2: Estimate the Causal Effect To estimate the causal effect, we pass the model above to estimate_causal_effect!. ```julia # Note that we could also estimate the ATT by setting quantity_of_interest="ATT" estimate_causal_effect!(g_computer) ``` ## Step 3: Get a Summary We can get a summary of the model by pasing the model to the summarize method. !!!note To calculate the p-value and standard error for the treatmetn effect, you can set the inference argument to false. However, p-values and standard errors are calculated via randomization inference, which will take a long time. But can be sped up by launching Julia with a higher number of threads. ```julia summarize(g_computer) ``` ## Step 4: Validate the Model We can validate the model by examining the plausibility that the main assumptions of causal inference, counterfactual consistency, exchangeability, and positivity, hold. It should be noted that consistency and exchangeability are not directly testable, so instead, these tests do not provide definitive evidence of a violation of these assumptions. To probe the counterfactual consistency assumption, we simulate counterfactual outcomes that are different from the observed outcomes, estimate models with the simulated counterfactual outcomes, and take the averages. If the outcome is continuous, the noise for the simulated counterfactuals is drawn from N(0, dev) for each element in devs and each outcome, multiplied by the original outcome, and added to the original outcome. For discrete variables, each outcome is replaced with a different value in the range of outcomes with probability ϵ for each ϵ in devs, otherwise the default is 0.025, 0.05, 0.075, 0.1. If the average estimate for a given level of violation differs greatly from the effect estimated on the actual data, then the model is very sensitive to violations of the counterfactual consistency assumption for that level of violation. Next, this method tests the model's sensitivity to a violation of the exchangeability assumption by calculating the E-value, which is the minimum strength of association, on the risk ratio scale, that an unobserved confounder would need to have with the treatment and outcome variable to fully explain away the estimated effect. Thus, higher E-values imply the model is more robust to a violation of the exchangeability assumption. Finally, this method tests the positivity assumption by estimating propensity scores. Rows in the matrix are levels of covariates that have a zero or near zero probability of treatment. If the matrix is empty, none of the observations have an estimated zero probability of treatment, which implies the positivity assumption is satisfied. !!! tip One can also specify the minimum and maximum probabilities of treatment for the positivity assumption with the num\_treatments, min, and max keyword arguments. !!! danger Obtaining correct estimates is dependent on meeting the assumptions for G-computation. If the assumptions are not met then any estimates may be biased and lead to incorrect conclusions. !!! note For a thorough review of casual inference assumptions see: Hernan, Miguel A., and James M. Robins. Causal inference what if. Boca Raton: Taylor and Francis, 2024. For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. ```julia validate(g_computer) ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
5935
# Interrupted Time Series Analysis Sometimes we want to know how an outcome variable for a single unit changed after an event or intervention. For example, if regulators announce sanctions against company A, we might want to know how the price of company A's stock changed after the announcement. Since we do not know what the price of Company A's stock would have been if the santions were not announced, we need some way to predict those values. An interrupted time series analysis does this by using some covariates that are related to the outcome but not related to whether the event happened to predict what would have happened. The estimated effects are the differences between the predicted post-event counterfactual outcomes and the observed post-event outcomes, which can also be aggregated to mean or cumulative effects. Estimating an interrupted time series design in CausalELM consists of three steps. !!! note For a general overview of interrupted time series estimation see: Bernal, James Lopez, Steven Cummins, and Antonio Gasparrini. "Interrupted time series regression for the evaluation of public health interventions: a tutorial." International journal of epidemiology 46, no. 1 (2017): 348-355. !!! note The flavor of interrupted time series implemented here is similar to the variant proposed in: Brodersen, Kay H., Fabian Gallusser, Jim Koehler, Nicolas Remy, and Steven L. Scott. "Inferring causal impact using Bayesian structural time-series models." (2015): 247-274. in that, although it is not Bayesian, it uses a nonparametric model of the pre-treatment period and uses that model to forecast the counterfactual in the post-treatment period, as opposed to the commonly used segment linear regression. ## Step 1: Initialize an interrupted time series estimator The InterruptedTimeSeries constructor takes at least four agruments: pre-event covariates, pre-event outcomes, post-event covariates, and post-event outcomes, all of which can be either an array or any data structure that implements the Tables.jl interface (e.g. DataFrames). The interrupted time series estimator assumes outcomes are either continuous, count, or time to event variables. !!! note Non-binary categorical outcomes are treated as continuous. !!! tip You can also specify which activation function to use, the number of extreme learning machines to use, the number of features to consider for each extreme learning machine, the number of bootstrapped observations to include in each extreme learning machine, and the number of neurons to use during estimation. These options are specified with the following keyword arguments: activation, num_machines, num_feats, sample_size, and num\_neurons. ```julia # Generate some data to use X₀, Y₀, X₁, Y₁ = rand(1000, 5), rand(1000), rand(100, 5), rand(100) # We could also use DataFrames or any other package that implements the Tables.jl interface # using DataFrames # X₀ = DataFrame(x1=rand(1000), x2=rand(1000), x3=rand(1000), x4=rand(1000), x5=rand(1000)) # X₁ = DataFrame(x1=rand(1000), x2=rand(1000), x3=rand(1000), x4=rand(1000), x5=rand(1000)) # Y₀, Y₁ = DataFrame(y=rand(1000)), DataFrame(y=rand(1000)) its = InterruptedTimeSeries(X₀, Y₀, X₁, Y₁) ``` ## Step 2: Estimate the Treatment Effect Estimating the treatment effect only requires one argument: an InterruptedTimeSeries struct. ```julia estimate_causal_effect!(its) ``` ## Step 3: Get a Summary We can get a summary of the model by pasing the model to the summarize method. !!!note To calculate the p-value and standard error for the treatmetn effect, you can set the inference argument to false. However, p-values and standard errors are calculated via randomization inference, which will take a long time. But can be sped up by launching Julia with a higher number of threads. ```julia summarize(its) ``` ## Step 4: Validate the Model For an interrupted time series design to work well we need to be able to get an unbiased prediction of the counterfactual outcomes. If the event or intervention effected the covariates we are using to predict the counterfactual outcomes, then we will not be able to get unbiased predictions. We can verify this by conducting a Chow Test on the covariates. An ITS design also assumes that any observed effect is due to the hypothesized intervention, rather than any simultaneous interventions, anticipation of the intervention, or any intervention that ocurred after the hypothesized intervention. We can use a Wald supremum test to see if the hypothesized intervention ocurred where there is the largest structural break in the outcome or if there was a larger, statistically significant break in the outcome that could confound an ITS analysis. The covariates in an ITS analysis should be good predictors of the outcome. If this is the case, then adding irrelevant predictors should not have much of a change on the results of the analysis. We can conduct all these tests in one line of code. !!! tip One can also specify the number of simulated confounders to generate to test the sensitivity of the model to confounding and the minimum and maximum proportion of data to use in the Wald supremum test by including the n, low, and high keyword arguments. !!! danger Obtaining correct estimates is dependent on meeting the assumptions for interrupted time series estimation. If the assumptions are not met then any estimates may be biased and lead to incorrect conclusions. !!! note For a review of interrupted time series identifying assumptions and robustness checks, see: Baicker, Katherine, and Theodore Svoronos. Testing the validity of the single interrupted time series design. No. w26080. National Bureau of Economic Research, 2019. ```julia validate(its) ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.7.0
fd8c488545df3b46ddd972b28d2a45f83414674a
docs
7403
# Metalearners Instead of knowing the average causal effect, we might want to know which units benefit and which units lose by being exposed to a treatment. For example, a cash transfer program might motivate some people to work harder and incentivize others to work less. Thus, we might want to know how the cash transfer program affects individuals instead of it average affect on the population. To do so, we can use metalearners. Depending on the scenario, we may want to use an S-learner, T-learner, X-learner, R-learner, or doubly robust learner. The basic steps to use all five metalearners are below. The difference between the metalearners is how they estimate the CATE and what types of variables they can handle. In the case of S, T, X, and doubly robust learners, they can only handle binary treatments. On the other hand, R-learners can handle binary, categorical, count, or continuous treatments but only supports continuous outcomes. !!! note For a deeper dive on S-learning, T-learning, and X-learning see: Künzel, Sören R., Jasjeet S. Sekhon, Peter J. Bickel, and Bin Yu. "Metalearners for estimating heterogeneous treatment effects using machine learning." Proceedings of the national academy of sciences 116, no. 10 (2019): 4156-4165. To learn more about R-learning see: Nie, Xinkun, and Stefan Wager. "Quasi-oracle estimation of heterogeneous treatment effects." Biometrika 108, no. 2 (2021): 299-319. To see the details out doubly robust estimation implemented in CausalELM see: Kennedy, Edward H. "Towards optimal doubly robust estimation of heterogeneous causal effects." Electronic Journal of Statistics 17, no. 2 (2023): 3008-3049. # Initialize a Metalearner S-learners, T-learners, X-learners, R-learners, and doubly robust estimators all take at least three arguments—covariates, treatment statuses, and outcomes, all of which can be either an array or any struct that implements the Tables.jl interface (e.g. DataFrames). S, T, X, and doubly robust learners support binary treatment variables and binary, continuous, count, or time to event outcomes. The R-learning estimator supports binary, continuous, or count treatment variables and binary, continuous, count, or time to event outcomes. !!! note Non-binary categorical outcomes are treated as continuous. !!! tip You can also specify the the number of folds to use for cross-fitting, the number of extreme learning machines to incorporate in the ensemble, the number of features to consider for each extreme learning machine, the activation function to use, the number of observations to bootstrap in each extreme learning machine, and the number of neurons in each extreme learning machine. These arguments are specified with the folds, num_machines, num_features, activation, sample_size, and num\_neurons keywords. ```julia # Generate data to use X, Y, T = rand(1000, 5), rand(1000), [rand()<0.4 for i in 1:1000] # We could also use DataFrames or any other package that implements the Tables.jl API # using DataFrames # X = DataFrame(x1=rand(1000), x2=rand(1000), x3=rand(1000), x4=rand(1000), x5=rand(1000)) # T, Y = DataFrame(t=[rand()<0.4 for i in 1:1000]), DataFrame(y=rand(1000)) s_learner = SLearner(X, Y, T) t_learner = TLearner(X, Y, T) x_learner = XLearner(X, Y, T) r_learner = RLearner(X, Y, T) dr_learner = DoublyRobustLearner(X, T, Y) ``` # Estimate the CATE We can estimate the CATE for all the models by passing them to estimate_causal_effect!. ```julia estimate_causal_effect!(s_learner) estimate_causal_effect!(t_learner) estimate_causal_effect!(x_learner) estimate_causal_effect!(r_learner) estimate_causal_effect!(dr_lwarner) ``` # Get a Summary We can get a summary of the model by pasing the model to the summarize method. !!!note To calculate the p-value and standard error for the treatmetn effect, you can set the inference argument to false. However, p-values and standard errors are calculated via randomization inference, which will take a long time. But can be sped up by launching Julia with a higher number of threads. ```julia summarize(s_learner) summarize(t_learner) summarize(x_learner) summarize(r_learner) summarize(dr_learner) ``` ## Step 4: Validate the Model We can validate the model by examining the plausibility that the main assumptions of causal inference, counterfactual consistency, exchangeability, and positivity, hold. It should be noted that consistency and exchangeability are not directly testable, so instead, these tests do not provide definitive evidence of a violation of these assumptions. To probe the counterfactual consistency assumption, we simulate counterfactual outcomes that are different from the observed outcomes, estimate models with the simulated counterfactual outcomes, and take the averages. If the outcome is continuous, the noise for the simulated counterfactuals is drawn from N(0, dev) for each element in devs and each outcome, multiplied by the original outcome, and added to the original outcome. For discrete variables, each outcome is replaced with a different value in the range of outcomes with probability ϵ for each ϵ in devs, otherwise the default is 0.025, 0.05, 0.075, 0.1. If the average estimate for a given level of violation differs greatly from the effect estimated on the actual data, then the model is very sensitive to violations of the counterfactual consistency assumption for that level of violation. Next, this method tests the model's sensitivity to a violation of the exchangeability assumption by calculating the E-value, which is the minimum strength of association, on the risk ratio scale, that an unobserved confounder would need to have with the treatment and outcome variable to fully explain away the estimated effect. Thus, higher E-values imply the model is more robust to a violation of the exchangeability assumption. Finally, this method tests the positivity assumption by estimating propensity scores. Rows in the matrix are levels of covariates that have a zero or near zero probability of treatment. If the matrix is empty, none of the observations have an estimated zero probability of treatment, which implies the positivity assumption is satisfied. !!! tip One can also specify the maxium number of possible treatments to consider for the causal consistency assumption and the minimum and maximum probabilities of treatment for the positivity assumption with the num\_treatments, min, and max keyword arguments. !!! danger Obtaining correct estimates is dependent on meeting the assumptions for interrupted time series estimation. If the assumptions are not met then any estimates may be biased and lead to incorrect conclusions. !!! note For a thorough review of casual inference assumptions see: Hernan, Miguel A., and James M. Robins. Causal inference what if. Boca Raton: Taylor and Francis, 2024. For more information on the E-value test see: VanderWeele, Tyler J., and Peng Ding. "Sensitivity analysis in observational research: introducing the E-value." Annals of internal medicine 167, no. 4 (2017): 268-274. ```julia validate(s_learner) validate(t_learner) validate(x_learner) validate(r_learner) validate(dr_learner) ```
CausalELM
https://github.com/dscolby/CausalELM.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
26858
# <!-- Create the .md file by running # Literate.markdown("./README.jl", flavor = Literate.CommonMarkFlavor()) --> # [![CI](https://github.com/enweg/BayesFlux.jl/actions/workflows/tests.yml/badge.svg)](https://github.com/enweg/BayesFlux.jl/actions/workflows/tests.yml) # [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://enweg.github.io/BayesFlux.jl/stable) # [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://enweg.github.io/BayesFlux.jl/dev) using BayesFlux, Flux using Random, Distributions using StatsPlots Random.seed!(6150533) # ## BayesFlux (Bayesian extension for Flux) # BayesFlux is meant to be an extension to Flux.jl, a machine learning # library written entirely in Julia. BayesFlux will and is not meant to be the # fastest production ready library, but rather is meant to make research and # experimentation easy. # BayesFlux is part of my Master Thesis in Economic and Financial Research - # specialisation Econometrics and will therefore likelily still go through some # revisions in the coming months. # ## Structure # # Every Bayesian model can in general be broken down into the probablistic # model, which gives the likelihood function and the prior on all parameters of # the probabilistic model. BayesFlux somewhat follows this and splits every Bayesian # Network into the following parts: # # 1. **Network**: Every BNN must have some general network structure. This is # defined using Flux and currently supports Dense, RNN, and LSTM layers. More # on this later # 2. **Network Constructor**: Since BayesFlux works with vectors of parameters, we # need to be able to go from a vector to the network and back. This works by # using the NetworkConstructor. # 3. **Likelihood**: The likelihood function. In traditional estimation of NNs, # this would correspond to the negative loss function. BayesFlux has a twist on # this though and nomenclature might change because of this twist: The # likelihood also contains all additional parameters and priors. For example, # for a Gaussian likelihood, the likelihood object also defines the standard # deviation and the prior for the standard deviation. This desing choice was # made to keep the likelihood and everything belonging to it separate from # the network; Again, due to the potential confusion, the nomenclature might # change in later revisions. # 4. **Prior on network parameters**: A prior on all network parameters. # Currently the RNN layers do not define priors on the initial state and thus # the initial state is also not sampled. Priors can have hyper-priors. # 5. **Initialiser**: Unless some special initialisation values are given, BayesFlux # will draw initial values as defined by the initialiser. An initialiser # initialises all network and likelihood parameters to reasonable values. # # All of the above are then used to create a BNN which can then be estimated # using the MAP, can be sampled from using any of the MCMC methods implemented, # or can be estimated using Variational Inference. # # The examples and the sections below hopefully clarify everything. If any # questions remain, please open an issue. # ## Linear Regression using BayesFlux # # Although not meant for Simple Linear Regression, BayesFlux can be used for it, and # we will do so in this section. This will hopefully demonstrate the basics. # Later sections will show better examples. # # Let's say we have the idea that the data can be modelled via a linear model of # the form # $$y_i = x_i'\beta + e_i$$ # with $e_i \sim N(0, 1)$ k = 5 n = 500 x = randn(Float32, k, n); β = randn(Float32, k); y = x'*β + randn(Float32, n); # # This is a standard linear model and we would likely be better off using STAN # or Turing for this, but due to the availability of a Dense layer with linear # activation function, we can also implent it in BayesFlux. # # The first step is to define the network. As mentioned above, the network # consists of a single Dense layer with a linear activation function (the # default activation in Flux and hence not explicitly shown). net = Chain(Dense(k, 1)) # k inputs and one output # Since BayesFlux works with vectors, we need to be able to transform a vector to # the above network and back. We thus need a NetworkConstructor, which we obtain # as a the return value of a `destruct` nc = destruct(net) # We can check whether everything work by just creating a random vector of the # right dimension and calling the NetworkConstructor using this vector. θ = randn(Float32, nc.num_params_network) nc(θ) # We indeed obtain a network of the right size and structure. # Next, we will define a prior for all parameters of the network. Since weight # decay is a popular regularisation method in standard ML estimation, we will be # using a Gaussian prior, which is the Bayesian weight decay: prior = GaussianPrior(nc, 0.5f0) # the last value is the standard deviation # We also need a likelihood and a prior on all parameters the likelihood # introduces to the model. We will go for a Gaussian likelihood, which # introduces the standard deviation of the model. BayesFlux currently implements # Gaussian and Student-t likelihoods for Feedforward and Seq-to-one cases but # more can easily be implemented. See **TODO HAR link** for an example. like = FeedforwardNormal(nc, Gamma(2.0, 0.5)) # Second argument is prior for standard deviation. # Lastly, when no explicit initial value is given, BayesFlux will draw it from an # initialiser. Currently only one type of initialiser is implemented in BayesFlux, # but this can easily be extended by the user itself. init = InitialiseAllSame(Normal(0.0f0, 0.5f0), like, prior) # First argument is dist we draw parameters from. # Given all the above, we can now define the BNN: bnn = BNN(x, y, like, prior, init) # ### MAP estimate. # # It is always a good idea to first find the MAP estimate. This can serve two # purposes: # # 1. It is faster than fully estimating the model using MCMC or VI and can thus # serve as a quick check; If the MAP estimate results in bad point # predictions, so will likely the full estimation results. # 2. It can serve as a starting value for the MCMC samplers. # # To find a MAP estimate, we must first specify how we want to find it: We need # to define an optimiser. BayesFlux currently only implements optimisers derived # from Flux itself, but this can be extended by the user. opt = FluxModeFinder(bnn, Flux.ADAM()) # We will use ADAM θmap = find_mode(bnn, 10, 500, opt) # batchsize 10 with 500 epochs # We can already use the MAP estimate to make some predictions and calculate the # RMSE. nethat = nc(θmap) yhat = vec(nethat(x)) sqrt(mean(abs2, y .- yhat)) # ### MCMC - SGLD # # If the MAP estimate does not show any problems, it can be used as the starting # point for SGLD or any of the other MCMC methods (see later section). # # Simulations have shown that using a relatively large initial stepsize with a # slow decaying stepsize schedule often results in the best mixing. *Note: We # would usually use samplers such as NUTS for linear regressions, which are much # more efficient than SGLD* sampler = SGLD(Float32; stepsize_a = 10f-0, stepsize_b = 0.0f0, stepsize_γ = 0.55f0) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] # We can obtain summary statistics and trace and density plots of network # parameters and likelihood parameters by transforming the BayesFlux chain into a # MCMCChain. using MCMCChains chain = Chains(ch') plot(chain) # In more complicated networks, it is usually a hopeless goal to obtain good # mixing in parameter space and thus we rather focus on the output space of the # network. *Mixing in parameter space is hopeless due to the very complicated # topology of the posterior; see ...* # We will use a little helper function to get the output values of the network: function naive_prediction(bnn, draws::Array{T, 2}; x = bnn.x, y = bnn.y) where {T} yhats = Array{T, 2}(undef, length(y), size(draws, 2)) Threads.@threads for i=1:size(draws, 2) net = bnn.like.nc(draws[:, i]) yh = vec(net(x)) yhats[:,i] = yh end return yhats end yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # Similarly, we can obtain posterior predictive values and evaluate quantiles # obtained using these to how many percent of the actual data fall below the # quantiles. What we would like is that 5% of the data fall below the 5% # quantile of the posterior predictive draws. function get_observed_quantiles(y, posterior_yhat, target_q = 0.05:0.05:0.95) qs = [quantile(yr, target_q) for yr in eachrow(posterior_yhat)] qs = reduce(hcat, qs) observed_q = mean(reshape(y, 1, :) .< qs; dims = 2) return observed_q end posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ### MCMC - SGNHTS # # Just like SGLD, SGNHTS also does not apply a Metropolis-Hastings correction # step. Contrary to SGLD though, SGNHTS implementes a Thermostat, whose task it # is to keep the temperature in the dynamic system close to one, and thus the # sampling more accurate. Although the thermostats goal is often not achieved, # samples obtained using SGNHTS often outperform those obtained using SGLD. sampler = SGNHTS(1f-2, 2f0; xi = 2f0^2, μ = 50f0) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ### MCMC - GGMC # # As pointed out above, neither SGLD nor SGNHTS apply a Metropolis-Hastings # acceptance step and are thus difficult to monitor. Indeed, draws from SGLD or # SGNHTS should perhaps rather be considered as giving and ensemble of models # rather than draws from the posterior, since without any MH step, it is unclear # whether the chain actually will converge to the posterior. # # BayesFlux also implements three methods that do apply a MH step and are thus # easier to monitor. These are GGMC, AdaptiveMH, and HMC. Both GGMC and HMC do # allow for taking stochastic gradients. GGMC also allows to use delayed # acceptance in which the MH step is only applied after a couple of steps, # rather than after each step (see ... for details). # # Because both GGMC and HMC use a MH step, they provide a measure of the mean # acceptance rate, which can be used to tune the stepsize using Dual Averaging # (see .../STAN for details). Similarly, both also make use of mass matrices, # which can also be tuned. # # BayesFlux implements both stepsize adapters and mass adapters but to this point # does not implement a smart way of combining them (this will come in the # future). In my experience, naively combining them often only helps in more # complex models and thus we will only use a stepsize adapter here. sadapter = DualAveragingStepSize(1f-9; target_accept = 0.55f0, adapt_steps = 10000) sampler = GGMC(Float32; β = 0.1f0, l = 1f-9, sadapter = sadapter) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # The above uses a MH correction after each step. This can be costly in big-data # environments or when the evaluation of the likelihood is costly. If either of # the above applies, delayed acceptance can speed up the process. sadapter = DualAveragingStepSize(1f-9; target_accept = 0.25f0, adapt_steps = 10000) sampler = GGMC(Float32; β = 0.1f0, l = 1f-9, sadapter = sadapter, steps = 3) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ### MCMC - HMC # # Since HMC showed some mixing problems for some variables during the testing of # this README, we decided to use a mass matrix adaptation. This turned out to # work better even in this simple case. sadapter = DualAveragingStepSize(1f-9; target_accept = 0.55f0, adapt_steps = 10000) madapter = DiagCovMassAdapter(5000, 1000) sampler = HMC(1f-9, 5; sadapter = sadapter) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ### MCMC - Adaptive Metropolis-Hastings # # As a derivative free alternative, BayesFlux also implements Adaptive MH as # introduced in (...). This is currently quite a costly method for complex # models since it needs to evaluate the MH ratio at each step. Plans exist to # parallelise the calculation of the likelihood which should speed up Adaptive # MH. sampler = AdaptiveMH(diagm(ones(Float32, bnn.num_total_params)), 1000, 0.5f0, 1f-4) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ### Variation Inference # # In some cases MCMC method either do not work well or even the methods above # take too long. For these cases BayesFlux currently implements Bayes-By-Backprop # (...); One shortcoming of the current implementation is that the variational # family is constrained to a diagonal multivariate gaussian and thus any # correlations between network parameters are set to zero. This can cause # problems in some situations and plans exist to allow for more felxible # covariance specifications. q, params, losses = bbb(bnn, 10, 2_000; mc_samples = 1, opt = Flux.ADAM(), n_samples_convergence = 10) ch = rand(q, 20_000) posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ## More complicated FNN # # What changes if I want to implement BNNs using more complicated Feedforward # structures than above? Nothing! Well, almost nothing. The only thing that # truly changes is the network you specify. All the rest could in theory stay # the same. As the network becomes more complicated, it might be worth it to # specify better priors or likelihoods though. Say, for example, we use the same # data as above (in reality we would not know that it is coming from a linear # model although it is always good practice to try simple models first), but # instead of using the above network structure corresponding to a linear model, # use the following: net = Chain(Dense(k, k, relu), Dense(k, k, relu), Dense(k, 1)) # We can then still use the same prior, likelihood, and initialiser. But we do # need to change the NetworkConstructor. nc = destruct(net) like = FeedforwardNormal(nc, Gamma(2.0, 0.5)) prior = GaussianPrior(nc, 0.5f0) init = InitialiseAllSame(Normal(0.0f0, 0.5f0), like, prior) bnn = BNN(x, y, like, prior, init) # The rest is the same as above. We can, for example, first find the MAP: opt = FluxModeFinder(bnn, Flux.ADAM()) # We will use ADAM θmap = find_mode(bnn, 10, 500, opt) # batchsize 10 with 500 epochs # ---- nethat = nc(θmap) yhat = vec(nethat(x)) sqrt(mean(abs2, y .- yhat)) # Or we can use any of the MCMC or VI method - SGNHTS is just one option: sampler = SGNHTS(1f-2, 1f0; xi = 1f0^2, μ = 10f0) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') # ---- yhats = naive_prediction(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # ## Recurrent Structures # # Next to Dense layers, BayesFlux also implements RNN and LSTM layers. These two do # require some additional care though, since the layout of the data must be # adjusted. In general, the last dimension of `x` and `y` is always the # dimension along which BayesFlux batches. Thus, if we are in a seq-to-one setting # - seq-to-seq is not implemented itself but users can implement custom # likelihoods to for a seq-to-seq setting - then the sequences must be along # the last dimension (here the third). To demonstrate this, let us simulate # sime AR1 data Random.seed!(6150533) gamma = 0.8 N = 500 burnin = 1000 y = zeros(N + burnin + 1) for t=2:(N+burnin+1) y[t] = gamma*y[t-1] + randn() end y = Float32.(y[end-N+1:end]) # Just like in the FNN case, we need a network structure and its constructor, a # prior on the network parameters, a likelihood with a prior on the additional # parameters introduced by the likelihood, and an initialiser net = Chain(RNN(1, 1), Dense(1, 1)) # last layer is linear output layer nc = destruct(net) like = SeqToOneNormal(nc, Gamma(2.0, 0.5)) prior = GaussianPrior(nc, 0.5f0) init = InitialiseAllSame(Normal(0.0f0, 0.5f0), like, prior) # We are given a single sequence (time series). To exploit batching and to not # always have to feed through the whole sequence, we will split the single # sequence into overlapping subsequences of length 5 and store these in a # tensor. Note that we add 1 to the subsequence length, because the last # observation of each subsequence will be our training observation to predict # using the fist five items in the subsequence. x = make_rnn_tensor(reshape(y, :, 1), 5 + 1) y = vec(x[end, :, :]) x = x[1:end-1, :, :] # We are now ready to create the BNN and find the MAP estimate. The MAP will be # used to check whether the overall network structure makes sense (does provide # at least good point estimates). bnn = BNN(x, y, like, prior, init) opt = FluxModeFinder(bnn, Flux.RMSProp()) θmap = find_mode(bnn, 10, 1000, opt) # When checking the performance we need to make sure to feed the sequences # through the network observation by observation: nethat = nc(θmap) yhat = vec([nethat(xx) for xx in eachslice(x; dims =1 )][end]) sqrt(mean(abs2, y .- yhat)) # The rest works just like before with some minor adjustments to the helper # functions. sampler = SGNHTS(1f-2, 1f0; xi = 1f0^2, μ = 10f0) ch = mcmc(bnn, 10, 50_000, sampler) ch = ch[:, end-20_000+1:end] chain = Chains(ch') function naive_prediction_recurrent(bnn, draws::Array{T, 2}; x = bnn.x, y = bnn.y) where {T} yhats = Array{T, 2}(undef, length(y), size(draws, 2)) Threads.@threads for i=1:size(draws, 2) net = bnn.like.nc(draws[:, i]) yh = vec([net(xx) for xx in eachslice(x; dims = 1)][end]) yhats[:,i] = yh end return yhats end # ---- yhats = naive_prediction_recurrent(bnn, ch) chain_yhat = Chains(yhats') maximum(summarystats(chain_yhat)[:, :rhat]) # ---- posterior_yhat = sample_posterior_predict(bnn, ch) t_q = 0.05:0.05:0.95 o_q = get_observed_quantiles(y, posterior_yhat, t_q) plot(t_q, o_q, label = "Posterior Predictive", legend=:topleft, xlab = "Target Quantile", ylab = "Observed Quantile") plot!(x->x, t_q, label = "Target") # # Customising BayesFlux # # BayesFlux is coded in such a way that the user can easily extend many of the # funcitonalities. The following are the easiest to extend and we will cover # them below: # # - Initialisers # - Layers # - Priors # - Likelihoods # # ## Customising Initialisers # # Every Initialiser must be implemented as a callable type extending the # abstract type `BNNInitialiser`. As aready mentioned, it must be callable, # with the only (optional) argument being a random number generator. It must # return a tupe of vectors: `(θnet, θhyper, θlike)` where any of the latter two # vectors is allowed to be of length zero. *For more information read the # documentation of `BNNInitialiser` # # **Example**: See the code for `InitialiseAllSame` # # ## Customising Layers # # BayesFlux relies on the layers currently implemented in `Flux`. Thus, the first step # in implementing a new layer for BayesFlux is to implement a new layer for `Flux`. # Once that is done, one must also implement a destruct method. For example, for # the Dense layer this has the following form function destruct(cell::Flux.Dense) @unpack weight, bias, σ = cell θ = vcat(vec(weight), vec(bias)) function re(θ::AbstractVector) s = 1 pweight = length(weight) new_weight = reshape(θ[s:s+pweight-1], size(weight)) s += pweight pbias = length(bias) new_bias = reshape(θ[s:s+pbias-1], size(bias)) return Flux.Dense(new_weight, new_bias, σ) end return θ, re end # The destruct method takes as input a cell with the type of the cell being the # newly implemented layer. It must return a vector containing all network # parameter that should be trained/inferred and a function that given a vector # of the right length can restruct the layer. **Note: Flux also implements a # general destructure and restructure method. In my experience, this often # caused problems in AD and thus until this is more stable, BayesFlux will stick # with this manual setup**. # # Care must be taken when cells are recurrent. The actual layer is then not an # `RNNCell`, but rather the full recurrent version: `Flux.Recur{RNNCell}`. Thus, # the destruct methos for `RNN` cells takes the following form: function destruct(cell::Flux.Recur{R}) where {R<:Flux.RNNCell} @unpack σ, Wi, Wh, b, state0 = cell.cell ## θ = vcat(vec(Wi), vec(Wh), vec(b), vec(state0)) θ = vcat(vec(Wi), vec(Wh), vec(b)) function re(θ::Vector{T}) where {T} s = 1 pWi = length(Wi) new_Wi = reshape(θ[s:s+pWi-1], size(Wi)) s += pWi pWh = length(Wh) new_Wh = reshape(θ[s:s+pWh-1], size(Wh)) s += pWh pb = length(b) new_b = reshape(θ[s:s+pb-1], size(b)) s += pb ## pstate0 = length(state0) ## new_state0 = reshape(θ[s:s+pstate0-1], size(state0)) new_state0 = zeros(T, size(state0)) return Flux.Recur(Flux.RNNCell(σ, new_Wi, new_Wh, new_b, new_state0)) end return θ, re end # As can be seen from the commented out lines, we are currently not inferring # the initial state. While this would be great and could theoretically be done # in a Bayesian setting, it also often seems to cause bad mixing and other # difficulties in the inferential process. # # ## Customising Priors # # BayesFlux implements priors as subtypes of the abstract type `NetworkPrior`. # Generally what happens when one calles `loglikeprior` is that BayesFlux splits the # vector into `θnet, θhyper, θlike` and calls the prior with `θnet` and # `θhyper`. The number of hyper-parameters is given in the prior type. As such, # BayesFlux in theory allows for simple to highly complex multi-level priors. The # hope is that this provides enough flexibility to encourage researchers to try # out different priors. *For more documentation, please see the docs for # `NetworkPrior` and for an example of a mixture scale prior check out the code # for `MixtureScalePrior`*. # # > :bangbang: Note that the prior defined here is only for the network. All # > additional priors for parameters needed by the likelihood are handled in the # > likelihood. This might at first sound odd, but nicely splits network # > specific things from likelihood specific things and thus should make BayesFlux # > more flexible. # # ## Customising Likelihoods # # Likelihoods are implemented as types extending the abstract type # `BNNLikelihood` and thus can be extended by implementing a new subtype. # Traditionally likelihood truly only refer to the likelihood. We decided to go # a somewhat unconventional way and decided to design BayesFlux in a way that # likelihood types also include the prior for all parameters they introduce. # This was done so that the network specification with priors and all is # separate from the likelihood specification. As such, these two parts can be # freely changed without changing any of the other? # # **Example**: Say we would like to implement a simple Gaussian likelihood for a # Feedforward structure (this is already implemented). Unless we predifine the # standard deviation of the # Gaussian, we will also estimate it, and thus we need a prior for it. While in # the traditional setting this would be covered in the prior type, here it is # covered in the likelihood type. Thus, the version as implemented in BayesFlux # takes upon construction also a prior distribution that shall be used for the # standard deviation. This prior does not have to have as its domain the real # line. It can also be constrained, such as a Gamma distribution, as long as the # code of the likelihood type makes sure to appropriately transform the # distribution to the real line. In the already implemented version this is done # using `Bijectors.jl`. # # The documentation for `BNNLikelihood` gives details about what exactly need to # be implemented.
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1178
using Documenter using BayesFlux push!(LOAD_PATH, "../src/") makedocs( sitename = "BayesFlux.jl Documentation", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true" ), pages = [ "Introduction" => [ "index.md", "introduction/linear-regression.md", "introduction/feedforward.md", "introduction/recurrent.md" ], "Bayesian Neural Networks" => [ "model/bnn.md", "model/sampling.md" ], "Likelihood Functions" => [ "likelihoods/interface.md", "likelihoods/feedforward.md", "likelihoods/seqtoone.md" ], "Network Priors" => [ "priors/interface.md", "priors/gaussian.md", "priors/mixturescale.md" ], "Inference" => [ "inference/map.md", "inference/mcmc.md", "inference/vi.md" ], "Initialisation" => ["initialise/init.md"], "Utils" => ["utils/recurrent.md"] ], modules = [BayesFlux] ) deploydocs( repo = "github.com/enweg/BayesFlux.jl.git", )
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2392
module BayesFlux include("./utils/gradient_utils.jl") include("./layers/dense.jl") include("./layers/recurrent.jl") include("./model/deconstruct.jl") export destruct export NetConstructor include("./likelihoods/abstract.jl") include("./likelihoods/feedforward.jl") include("./likelihoods/seq_to_one.jl") export BNNLikelihood, posterior_predict export FeedforwardNormal, FeedforwardTDist export SeqToOneNormal, SeqToOneTDist include("./netpriors/abstract.jl") include("./netpriors/gaussian.jl") include("./netpriors/mixturescale.jl") export NetworkPrior, sample_prior export GaussianPrior export MixtureScalePrior include("./initialisers/abstract.jl") include("./initialisers/basics.jl") export BNNInitialiser export InitialiseAllSame include("./model/BNN.jl") export BNN export split_params export loglikeprior, ∇loglikeprior export sample_prior_predictive, get_posterior_networks, sample_posterior_predict include("./inference/mode/abstract.jl") include("./inference/mode/flux.jl") export BNNModeFinder, find_mode, step! export FluxModeFinder # Abstract MCMC include("./inference/mcmc/abstract.jl") # Mass Adapters include("./inference/mcmc/adapters/mass/abstract_mass.jl") include("./inference/mcmc/adapters/mass/diagcovariancemassadapter.jl") include("./inference/mcmc/adapters/mass/fixedmassmatrix.jl") include("./inference/mcmc/adapters/mass/fullcovariancemassadapter.jl") include("./inference/mcmc/adapters/mass/rmspropmassadapter.jl") export MassAdapter export DiagCovMassAdapter, FixedMassAdapter, FullCovMassAdapter, RMSPropMassAdapter # Stepsize Adapters include("./inference/mcmc/adapters/stepsize/abstract_stepsize.jl") include("./inference/mcmc/adapters/stepsize/constantstepsize.jl") include("./inference/mcmc/adapters/stepsize/dualaveragestepsize.jl") export StepsizeAdapter export ConstantStepsize, DualAveragingStepSize # MCMC Methods include("./inference/mcmc/sgld.jl") include("./inference/mcmc/sgnht.jl") include("./inference/mcmc/sgnht-s.jl") include("./inference/mcmc/ggmc.jl") include("./inference/mcmc/amh.jl") include("./inference/mcmc/hmc.jl") export MCMCState, mcmc export SGLD export SGNHT export SGNHTS export GGMC export AdaptiveMH export HMC # Variational Inference Methods # include("./inference/vi/advi.jl") include("./inference/vi/bbb.jl") # export advi export bbb # Utilities include("./utils/rnn_utils.jl") export make_rnn_tensor end # module
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
4174
""" abstract type MCMCState end Every MCMC method must be implemented via a MCMCState which keeps track of all important information. # Mandatory Fields - `samples::Matrix` of dimension num_total_parameter×num_samples - `nsampled` the number of thus far sampled samples # Mandatory Functions - `update!(sampler, θ, bnn, ∇θ)` where θ is the current parameter vector and ∇θ(θ) is a function providing gradients. The function must return θ and num_samples so far sampled. - `initialise!(sampler, θ, numsamples; continue_sampling)` which initialises the sampler. If continue_sampling is true, then the final goal is to obtain numsamples samples and thus only the remaining ones still need to be sampled. - `calculate_epochs(sampler, numbatches, numsamples; continue_sampling)` which calculates the number of epochs that must be run through in order to obtain `numsamples` samples if `numbatches` batches are used. The number of epochs must be returned. If `continue_sampling` is true, then the goal is to obtain in total `numsamples` samples and thus we only need the number of epochs that still need to be run to obtain this total and NOT the number of epochs to sample `numsamples` new samples. """ abstract type MCMCState end function calculate_epochs( sampler::MCMCState, nbatches, nsamples; continue_sampling=false ) error("$(typeof(sampler)) did not implement a calculate_epochs method. Please consult the documentation for MCMCState") end function update!( sampler::MCMCState, θ::AbstractVector{T}, bnn::BNN, ∇θ ) where {T} error("$(typeof(sampler)) has not implemented an update! method. Please consult the documentation for MCMCState") end """ mcmc(args...; kwargs...) Sample from a BNN using MCMC # Arguments - `bnn`: a Bayesian Neural Network - `batchsize`: batchsize - `numsamples`: number of samples to take - `sampler`: sampler to use # Keyword Arguments - `shuffle::Bool=true`: should data be shuffled after each epoch such that batches are different in each epoch? - `partial::Bool=true`: are partial batches allowed? If true, some batches might be smaller than `batchsize` - `showprogress::Bool=true`: should a progress bar be shown? - `continue_sampling::Bool=false`: If true and `numsamples` is larger than `sampler.nsampled` then additional samples will be taken - `θstart::AbstractVector{T}=vcat(bnn.init()...)`: starting parameter vector """ function mcmc( bnn::BNN, batchsize::Int, numsamples::Int, sampler::MCMCState; shuffle=true, partial=true, showprogress=true, continue_sampling=false, θstart::AbstractVector{T}=vcat(bnn.init()...) ) where {T} if !partial && !shuffle @warn """shuffle and partial should not be both false unless the data is perfectly divided by the batchsize. If this is not the case, some data would never be considered""" end # This allows to stop sampling and continue later if continue_sampling θ = sampler.samples[:, end] else θ = θstart end @info "Starting sampling at $θ" @info "Stating lπ = $(loglikeprior(bnn, θ, bnn.x, bnn.y))" batcher = Flux.Data.DataLoader((x=bnn.x, y=bnn.y), batchsize=batchsize, shuffle=shuffle, partial=partial) num_batches = length(batcher) tosample = continue_sampling ? numsamples - sampler.nsampled : numsamples prog = Progress(tosample; desc="Sampling...", enabled=showprogress, showspeed=true) ∇θ(θ, x, y) = ∇loglikeprior(bnn, θ, x, y; num_batches=num_batches) initialise!(sampler, θ, numsamples; continue_sampling=continue_sampling) epochs = calculate_epochs(sampler, num_batches, numsamples; continue_sampling=continue_sampling) @info "Running for $epochs epochs." nsampled = continue_sampling ? sampler.nsampled : 0 for e = 1:epochs for (x, y) in batcher nsampled == numsamples && break θ = update!(sampler, θ, bnn, θ -> ∇θ(θ, x, y)) nsampled = sampler.nsampled ProgressMeter.update!(prog, nsampled) end end return sampler.samples end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3541
""" Adaptive Metropolis Hastings as introduced in Haario, H., Saksman, E., & Tamminen, J. (2001). An adaptive Metropolis algorithm. Bernoulli, 223-242. # Fields - `samples::Matix`: Matrix holding the samples. If sampling was stopped early, not all columns will represent samples. To figure out how many columns represent samples, check out `nsampled`. - `nsampled::Int`: Number of samples obtained. - `C0::Matrix`: Initial covariance matrix. - `Ct::Matrix`: Covariance matrix in iteration t - `t::Int`: Current time period - `t0::Int`: When to start adaptig the covariance matrix? Covariance is adapted in a rolling window form. - `sd::T`: See the paper. - `ϵ::T`: Will be added to diagonal to prevent numerical non-pod-def problems. If you run into numerical problems, try increasing this values. - `accepted::Vector{Bool}`: For each sample, indicating whether the sample was accepted (true) or the previous samples was chosen (false) # Notes - Adaptive MH might not be suited if it is very costly to calculate the likelihood as this needs to be done for each sample on the full dataset. Plans exist to make this faster. - Works best when started at a MAP estimate. """ mutable struct AdaptiveMH{T} <: MCMCState samples::Matrix{T} nsampled::Int C0::Matrix{T} Ct::Matrix{T} t::Int t0::Int sd::T ϵ::T accepted::Vector{Bool} end """ function AdaptiveMH(C0::Matrix{T}, t0::Int, sd::T, ϵ::T) where {T} Construct an Adaptive MH sampler. # Arguments - `C0`: Initial covariance matrix. Can usually be chosen to be the identity matrix created using `diagm(ones(T, bnn.num_total_params))` - `t0`: Lookback window for adaptation of covariance matrix. Also means that adaptation does not happen until at least `t0` samples were drawn. - `sd`: See paper. - `ϵ`: Used to overcome numerical problems. """ function AdaptiveMH(C0::Matrix{T}, t0::Int, sd::T, ϵ::T) where {T} return AdaptiveMH(Matrix{T}(undef, 1, 1), 0, C0, similar(C0), 1, t0, sd, ϵ, Bool[]) end function initialise!( s::AdaptiveMH{T}, θ::AbstractVector{T}, nsamples::Int; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] end t = continue_sampling ? s.nsampled + 1 : 1 nsampled = continue_sampling ? s.nsampled : 0 Ct = continue_sampling ? s.Ct : s.C0 s.samples = samples s.nsampled = nsampled s.Ct = Ct s.t = t s.accepted = fill(false, nsamples) end function calculate_epochs( s::AdaptiveMH{T}, nbatches, nsamples; continue_sampling=false ) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples / nbatches) return epochs end function update!(s::AdaptiveMH{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} if s.t > s.t0 # Adapt covariance matrix. The paper actually states a more efficient way. # TODO: implement the more efficient way. s.Ct = s.sd * cov(s.samples[:, s.nsampled-s.t0+1:s.nsampled]') + s.sd * s.ϵ * I end θprop = rand(MvNormal(θ, s.Ct)) lMH = loglikeprior(bnn, θprop, bnn.x, bnn.y) - loglikeprior(bnn, θ, bnn.x, bnn.y) r = rand() if r < exp(lMH) s.samples[:, s.nsampled+1] = copy(θprop) s.accepted[s.nsampled+1] = true θ = θprop else s.samples[:, s.nsampled+1] = copy(θ) end s.nsampled += 1 s.t += 1 return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
5199
using LinearAlgebra """ Gradient Guided Monte Carlo Proposed in Garriga-Alonso, A., & Fortuin, V. (2021). Exact langevin dynamics with stochastic gradients. arXiv preprint arXiv:2102.01691. # Fields - `samples::Matrix`: Matrix containing the samples. If sampling stopped early, then not all columns will actually correspond to samples. See `nsampled` to check how many samples were actually taken - `nsampled::Int`: Number of samples taken. - `t::Int`: Total number of steps taken. - `accepted::Vector{Bool}`: If true, sample was accepted; If false, proposed sample was rejected and previous sample was taken. - `β::T`: See paper. - `l::T`: Step-length; See paper. - `sadapter::StepsizeAdapter`: A StepsizeAdapter. Default is `DualAveragingStepSize` - `M::AbstractMatrix`: Mass Matrix - `Mhalf::AbstractMatrix`: Lower triangual cholesky decomposition of `M` - `Minv::AbstractMatrix`: Inverse mass matrix. - `madapter::MassAdapter`: A MassAdapter - `momentum::AbstractVector`: Last momentum vector - `lMH::T`: log of Metropolis-Hastings ratio. - `steps::Int`: Number of steps to take before calculating MH ratio. - `current_step::Int`: Current step in the recurrent sequence 1, ..., `steps`. - `maxnorm::T`: Maximimum gradient norm. Gradients are being clipped if norm exceeds this value """ mutable struct GGMC{T} <: MCMCState samples::Matrix{T} nsampled::Int t::Int accepted::Vector{Int} β::T l::T sadapter::StepsizeAdapter M::AbstractMatrix{T} # Mass Matrix Mhalf::AbstractMatrix{T} Minv::AbstractMatrix{T} madapter::MassAdapter momentum::AbstractVector{T} lMH::T steps::Int # Delayed acceptance current_step::Int maxnorm::T # maximum gradient norm end function GGMC( type=Float32; β::T=0.55f0, l::T=0.0001f0, sadapter::StepsizeAdapter=DualAveragingStepSize(l), madapter::MassAdapter=DiagCovMassAdapter(1000, 100), steps::Int=1, maxnorm::T=5.0f0 ) where {T} samples = Matrix{type}(undef, 1, 1) nsampled = 0 t = 1 accepted = Int[] M, Mhalf, Minv = diagm(ones(T, 1)), diagm(ones(T, 1)), diagm(ones(T, 1)) momentum = zeros(T, 1) return GGMC( samples, nsampled, t, accepted, β, l, sadapter, M, Mhalf, Minv, madapter, momentum, T(0), steps, 1, maxnorm ) end function initialise!( s::GGMC{T}, θ::AbstractVector{T}, nsamples; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) accepted = zeros(Int, nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] accepted[1:s.nsampled] = s.accepted end t = continue_sampling ? s.t : 1 nsampled = continue_sampling ? s.nsampled : 0 s.samples = samples s.t = t s.nsampled = nsampled s.accepted = accepted s.current_step = 1 n = length(θ) if !continue_sampling s.M, s.Mhalf, s.Minv = diagm(ones(T, n)), diagm(ones(T, n)), diagm(ones(T, n)) end s.momentum = zeros(T, n) end function calculate_epochs( s::GGMC{T}, nbatches, nsamples; continue_sampling=false ) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples / nbatches) return epochs end K(m, Minv) = 1 / 2 * m' * Minv * m function update!(s::GGMC{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} γ = -sqrt(length(bnn.y) / s.l) * log(s.β) h = sqrt(s.l / length(bnn.y)) a = exp(-γ * h) if s.current_step == 1 s.lMH = -loglikeprior(bnn, θ, bnn.x, bnn.y) end v, g = ∇θ(θ) g = -g g = clip_gradient!(g; maxnorm=s.maxnorm) h = sqrt(h) momentum = s.momentum momentum14 = sqrt(a) * momentum + sqrt((T(1) - a)) * s.Mhalf * randn(length(θ)) momentum12 = momentum14 .- h / T(2) * g θ .+= h * s.Minv * momentum12 if any(isnan.(θ)) error("NaN in θ") end v, g = ∇θ(θ) g = -g g = clip_gradient!(g; maxnorm=s.maxnorm) momentum34 = momentum12 - h / T(2) * g s.momentum = sqrt(a) * momentum34 + sqrt((1 - a)) * s.Mhalf * rand(Normal(T(0), T(1)), length(θ)) s.lMH += K(momentum34, s.Minv) - K(momentum14, s.Minv) s.samples[:, s.t] = copy(θ) s.nsampled += 1 if s.current_step == s.steps && s.t > s.steps s.lMH += loglikeprior(bnn, θ, bnn.x, bnn.y) s.l = s.sadapter(s, min(exp(s.lMH), 1)) s.Minv = s.madapter(s, θ, bnn, ∇θ) s.M = inv(s.Minv) s.Mhalf = cholesky(s.M; check=false).L r = rand() if r < min(exp(s.lMH), 1) #|| s.nsampled == 1 # accepting s.accepted[(s.nsampled-s.steps+1):s.nsampled] = ones(Int, s.steps) else # rejecting s.samples[:, (s.nsampled-s.steps+1):s.nsampled] = hcat(fill(copy(s.samples[:, s.nsampled-s.steps]), s.steps)...) θ = copy(s.samples[:, s.nsampled-s.steps]) end end s.t += 1 s.current_step = (s.current_step == s.steps) ? 1 : s.current_step + 1 return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
4780
using LinearAlgebra """ Standard Hamiltonian Monte Carlo (Hybrid Monte Carlo). Allows for the use of stochastic gradients, but the validity of doing so is not clear. This is motivated by parts of the discussion in Neal, R. M. (1996). Bayesian Learning for Neural Networks (Vol. 118). Springer New York. https://doi.org/10.1007/978-1-4612-0745-0 Code was partially adapted from https://colindcarroll.com/2019/04/11/hamiltonian-monte-carlo-from-scratch/ # Fields - `samples::Matrix`: Samples taken - `nsampled::Int`: Number of samples taken. Might be smaller than `size(samples)` if sampling was interrupted. - `θold::AbstractVector`: Old sample. Kept for rejection step. - `momentum::AbstractVector`: Momentum variables - `momentumold::AbstractVector`: Old momentum variables. Kept for rejection step. - `t::Int`: Current step. - `path_len::Int`: Number of leapfrog steps. - `current_step::Int`: Current leapfrog step. - `accepted::Vector{Bool}`: Whether a draw in `samples` was a accepted draw or rejected (in which case it is the same as the previous one.) - `sadapter::StepsizeAdapter`: Stepsize adapter giving the stepsize in each iteration. - `l`: Stepsize. - `madapter::MassAdapter`: Mass matrix adapter giving the inverse mass matrix in each iteration. - `Minv::AbstractMatrix`: Inverse mass matrix - `maxnorm::T`: Maximimum gradient norm. Gradients are being clipped if norm exceeds this value """ mutable struct HMC{T} <: MCMCState samples::Matrix{T} nsampled::Int θold::AbstractVector{T} momentum::AbstractVector{T} momentumold::AbstractVector{T} t::Int path_len::Int # Leapfrog steps current_step::Int # which step of leapfrog steps accepted::Vector{Bool} sadapter::StepsizeAdapter l::T madapter::MassAdapter Minv::AbstractMatrix{T} maxnorm::T # maximum gradient norm end function HMC( l::T, path_len::Int; sadapter=DualAveragingStepSize(l), madapter=FullCovMassAdapter(1000, 100), maxnorm::T=5.0f0 ) where {T} return HMC(Matrix{T}(undef, 1, 1), 0, T[], T[], T[], 1, path_len, 1, Bool[], sadapter, l, madapter, Matrix{T}(undef, 0, 0), maxnorm) end function initialise!( s::HMC{T}, θ::AbstractVector{T}, nsamples::Int; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) accepted = fill(false, nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] accepted[1:s.nsampled] = s.accepted end t = continue_sampling ? s.nsampled + 1 : 1 nsampled = continue_sampling ? s.nsampled : 0 s.samples = samples s.nsampled = nsampled s.t = t s.accepted = accepted s.θold = copy(θ) s.momentum = zero(θ) s.momentumold = zero(θ) s.l = s.sadapter.l s.Minv = size(s.madapter.Minv, 1) == 0 ? Diagonal(one.(θ)) : s.madapter.Minv end function calculate_epochs(s::HMC{T}, nbatches, nsamples; continue_sampling=false) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples * s.path_len / nbatches) return epochs end function half_moment_update!(s::HMC{T}, θ::AbstractVector{T}, ∇θ) where {T} v, g = ∇θ(θ) g = -g # everyone else works with negative loglikeprior # Clipping g = clip_gradient!(g; maxnorm=s.maxnorm) s.momentum .-= s.l * g / T(2) end function update!(s::HMC{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} moment_dist = MvNormal(zero(θ), s.Minv) if s.current_step == 1 # New Leapfrog s.momentum = rand(moment_dist) s.θold = copy(θ) s.momentumold = copy(s.momentum) half_moment_update!(s, θ, ∇θ) elseif s.current_step < s.path_len # Leapfrog loop θ .+= s.l * s.momentum half_moment_update!(s, θ, ∇θ) else # Finishing off leapfrog and accept / reject θ .+= s.l * s.momentum half_moment_update!(s, θ, ∇θ) # moment flip s.momentum = -s.momentum start_mh = -loglikeprior(bnn, s.θold, bnn.x, bnn.y) - logpdf(moment_dist, s.momentumold) end_mh = -loglikeprior(bnn, θ, bnn.x, bnn.y) - logpdf(moment_dist, s.momentum) lMH = start_mh - end_mh lr = log(rand()) s.l = s.sadapter(s, min(exp(lMH), 1)) s.Minv = s.madapter(s, θ, bnn, ∇θ) if lr < lMH # accepting s.samples[:, s.nsampled+1] = copy(θ) s.accepted[s.nsampled+1] = true else # rejecting s.samples[:, s.nsampled+1] = copy(s.θold) θ = copy(s.θold) end s.nsampled += 1 end s.current_step = s.current_step == s.path_len ? 1 : s.current_step + 1 s.t += 1 return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2929
# implementation of stochastic gradient langevin dynamics """ stepsize(a, b, γ, t) Calculate the stepsize. Calculates the next stepsize according to ϵₜ = a(b+t)^(-γ). This is a commonly used stepsize schedule that meets the criteria ∑ϵₜ = ∞, ∑ϵₜ² < ∞. """ stepsize(a, b, γ, t) = a * (b + t)^(-γ) """ Stochastic Gradient Langevin Dynamics as proposed in Welling, M., & Teh, Y. W. (n.d.). Bayesian Learning via Stochastic Gradient Langevin Dynamics. 8. # Fields - `θ::AbstractVector`: Current sample - `samples::Matrix`: Matrix of samples. Not all columns will be actual samples if sampling was stopped early. See `nsampled` for the actual number of samples taken. - `nsampled::Int`: Number of samples taken - `min_stepsize::T`: Stop decreasing the stepsize when it is below this value. - `didinform::Bool`: Flag keeping track of whether we informed user that `min_stepsize` was reached. - `stepsize_a::T`: See `stepsize` - `stepsize_b::T`: See `stepsize` - `stepsize_γ::T`: See `stepsize` - `maxnorm::T`: Maximimum gradient norm. Gradients are being clipped if norm exceeds this value """ mutable struct SGLD{T} <: MCMCState θ::AbstractVector{T} samples::Matrix{T} nsampled::Int t::Int min_stepsize::T didinform::Bool stepsize_a::T stepsize_b::T stepsize_γ::T maxnorm::T # maximum norm of gradient end function SGLD( type=Float32; stepsize_a=0.1f0, stepsize_b=1.0f0, stepsize_γ=0.55f0, min_stepsize=Float32(-Inf), maxnorm=25.0f0 ) return SGLD( type[], Matrix{type}(undef, 1, 1), 0, 1, min_stepsize, false, stepsize_a, stepsize_b, stepsize_γ, maxnorm ) end function initialise!( s::SGLD{T}, θ::AbstractVector{T}, nsamples::Int; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] end t = continue_sampling ? s.nsampled + 1 : 1 nsampled = continue_sampling ? s.nsampled : 0 s.θ = θ s.samples = samples s.t = t s.nsampled = nsampled end function calculate_epochs(s::SGLD{T}, nbatches, nsamples; continue_sampling=false) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples / nbatches) return epochs end function update!(s::SGLD{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} α = stepsize(s.stepsize_a, s.stepsize_b, s.stepsize_γ, s.t) α < s.min_stepsize && !s.didinform && @info "Using minstepsize=$(s.min_stepsize) from now." α = max(α, s.min_stepsize) v, g = ∇θ(θ) g = clip_gradient!(g; maxnorm = s.maxnorm) g = α / T(2) .* g .+ sqrt(α) * randn(T, length(θ)) θ .+= g s.samples[:, s.t] = copy(θ) s.nsampled += 1 s.t += 1 s.θ = θ return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3243
""" Stochastic Gradient Nose-Hoover Thermostat as proposed in Proposed in Leimkuhler, B., & Shang, X. (2016). Adaptive thermostats for noisy gradient systems. SIAM Journal on Scientific Computing, 38(2), A712-A736. This is similar to SGNHT as proposed in Ding, N., Fang, Y., Babbush, R., Chen, C., Skeel, R. D., & Neven, H. (2014). Bayesian sampling using stochastic gradient thermostats. Advances in neural information processing systems, 27. # Fields - `samples::Matrix`: Containing the samples - `nsampled::Int`: Number of samples taken so far. Can be smaller than `size(samples, 2)` if sampling was interrupted. - `p::AbstractVector`: Momentum - `xi::Number`: Thermostat - `l::Number`: Stepsize; This often is in the 0.001-0.1 range. - `σA::Number`: Diffusion factor; If the stepsize is small, this should be larger than 1. - `μ::Number`: Free parameter in thermostat. Defaults to 1. - `t::Int`: Current step count - `kinetic::Vector`: Keeps track of the kinetic energy. Goal of SGNHT is to have the average close to one """ mutable struct SGNHTS{T} <: MCMCState samples::Matrix{T} nsampled::Int p::AbstractVector{T} xi::T l::T σA::T μ::T t::Int kinetic::Vector{T} madapter::MassAdapter end function SGNHTS( l::T, σA::T=T(1); xi=T(1), μ=T(1), madapter::MassAdapter=FixedMassAdapter() ) where {T} SGNHTS(Matrix{T}(undef, 0, 0), 0, T[], xi, l, σA, μ, 1, T[], madapter) end function initialise!( s::SGNHTS{T}, θ::AbstractVector{T}, nsamples::Int; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) kinetic = Vector{T}(undef, nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] kinetic[1:s.nsampled] = s.kinetic end t = continue_sampling ? s.nsampled + 1 : 1 nsampled = continue_sampling ? s.nsampled : 0 s.samples = samples s.kinetic = kinetic s.nsampled = nsampled s.t = t s.p = zero(θ) end function calculate_epochs(s::SGNHTS{T}, nbatches, nsamples; continue_sampling=false) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples / nbatches) return epochs end function update!(s::SGNHTS{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} Minv = s.madapter(s, θ, bnn, ∇θ) dist = MvNormal(zero.(θ), inv(Minv)) v, g = ∇θ(θ) # They work with potential energy which is negative loglike so negate # gradient g = -g if any(isnan.(g)) error("NaN in g") end n = length(θ) s.p = s.p - s.l / T(2) * g θ = θ + s.l / T(2) * Minv * s.p s.xi = s.xi + s.l / (T(2) * s.μ) * (s.p' * Minv * s.p - n) # We need kT = 1 if s.xi != 0 s.p = exp(-s.xi * s.l) * s.p + s.σA * sqrt((1 - exp(-T(2) * s.xi * s.l)) / (T(2) * s.xi)) * rand(dist) else s.p = s.p + sqrt(s.l) * s.σA * rand(dist) end s.xi = s.xi + s.l / (T(2) * s.μ) * (s.p' * Minv * s.p - n) θ = θ + s.l / T(2) * Minv * s.p if any(isnan.(θ)) error("NaN in θ") end s.samples[:, s.t] = copy(θ) s.kinetic[s.t] = 1 / n * s.p' * Minv * s.p s.t += 1 s.nsampled += 1 return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2399
""" Stochastic Gradient Nose-Hoover Thermostat as proposed in Ding, N., Fang, Y., Babbush, R., Chen, C., Skeel, R. D., & Neven, H. (2014). Bayesian sampling using stochastic gradient thermostats. Advances in neural information processing systems, 27. # Fields - `samples::Matrix`: Containing the samples - `nsampled::Int`: Number of samples taken so far. Can be smaller than `size(samples, 2)` if sampling was interrupted. - `p::AbstractVector`: Momentum - `xi::Number`: Thermostat - `l::Number`: Stepsize - `A::Number`: Diffusion factor - `t::Int`: Current step count - `kinetic::Vector`: Keeps track of the kinetic energy. Goal of SGNHT is to have the average close to one """ mutable struct SGNHT{T} <: MCMCState samples::Matrix{T} nsampled::Int p::AbstractVector{T} xi::T l::T A::T t::Int kinetic::Vector{T} end SGNHT(l::T, A::T=T(1); xi=T(0)) where {T} = SGNHT(Matrix{T}(undef, 0, 0), 0, T[], xi, l, A, 1, T[]) function initialise!( s::SGNHT{T}, θ::AbstractVector{T}, nsamples::Int; continue_sampling=false ) where {T} samples = Matrix{T}(undef, length(θ), nsamples) kinetic = Vector{T}(undef, nsamples) if continue_sampling samples[:, 1:s.nsampled] = s.samples[:, 1:s.nsampled] kinetic[1:s.nsampled] = s.kinetic end t = continue_sampling ? s.nsampled + 1 : 1 nsampled = continue_sampling ? s.nsampled : 0 s.samples = samples s.kinetic = kinetic s.nsampled = nsampled s.t = t s.p = zero(θ) end function calculate_epochs(s::SGNHT{T}, nbatches, nsamples; continue_sampling=false) where {T} n_newsamples = continue_sampling ? nsamples - s.nsampled : nsamples epochs = ceil(Int, n_newsamples / nbatches) return epochs end function update!(s::SGNHT{T}, θ::AbstractVector{T}, bnn::BNN, ∇θ) where {T} v, g = ∇θ(θ) # They work with potential energy which is negative loglike so negate # gradient g = -g if any(isnan.(g)) error("NaN in g") end s.p = s.p - s.xi * s.l * s.p - s.l * g + sqrt(s.l * 2 * s.A) * rand(MvNormal(zero.(θ), one.(θ))) θ = θ + s.l * s.p n = length(θ) kinetic = T(1) / n * s.p' * s.p s.kinetic[s.t] = kinetic s.xi = s.xi + (kinetic - 1) * s.l if any(isnan.(θ)) error("NaN in θ") end s.samples[:, s.t] = copy(θ) s.t += 1 s.nsampled += 1 return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
515
""" Adapt the mass matrix in MCMC and especially dynamic MCMC methods such as HMC, GGMC, SGLD, SGNHT, ... ## Mandatory Fields - `Minv::AbstractMatrix`: The inverse mass matrix used in HMC, GGMC, ... ## Mandatory Functions - `(madapter::MassAdapter)(s::MCMCState, θ::AbstractVector, bnn, ∇θ)`: Every mass adapter must be callable and have the sampler state, the current sample, the BNN and a gradient function as arguments. It must return the new `Minv` Matrix. """ abstract type MassAdapter end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1528
""" Use the variances as the diagonal of the inverse mass matrix as used in HMC, GGMC, ...; # Fields - `Minv`: Inverse mass matrix as used in HMC, SGLD, GGMC, ... - `adapt_steps`: Number of adaptation steps. - `windowlength`: Lookback length for calculation of covariance. - `t`: Current step. - `kappa`: How much to shrink towards the identity. - `epsilon`: Small value to add to diagonal to avoid numerical instability. """ mutable struct DiagCovMassAdapter{T} <: MassAdapter Minv::AbstractMatrix{T} adapt_steps::Int windowlength::Int t::Int kappa::T epsilon::T end function DiagCovMassAdapter( adapt_steps::Int, windowlength::Int; Minv::AbstractMatrix=Matrix(undef, 0, 0), kappa::T=0.5f0, epsilon=1.0f-6 ) where {T} size(Minv, 1) == 0 && (Minv = Matrix{T}(undef, 0, 0)) return DiagCovMassAdapter(Minv, adapt_steps, windowlength, 1, kappa, epsilon) end function (madapter::DiagCovMassAdapter{T})(s::MCMCState, θ::AbstractVector{T}, bnn::BNN, ∇θ ) where {T} madapter.t == 1 && size(madapter.Minv, 1) == 0 && (madapter.Minv = Diagonal(one.(θ))) madapter.t > madapter.adapt_steps && return madapter.Minv madapter.windowlength > s.nsampled && return madapter.Minv madapter.Minv = (T(1) - madapter.kappa) * Diagonal(vec(var(permutedims(s.samples[:, s.nsampled-madapter.windowlength+1:s.nsampled]); dims=1))) + madapter.kappa * I madapter.Minv = madapter.Minv + madapter.epsilon * I madapter.t += 1 return madapter.Minv end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
390
using LinearAlgebra """ Use a fixed inverse mass matrix. """ mutable struct FixedMassAdapter <: MassAdapter Minv::AbstractMatrix end FixedMassAdapter() = FixedMassAdapter(Matrix(undef, 0, 0)) function (madapter::FixedMassAdapter)(s::MCMCState, θ::AbstractVector{T}, bnn, ∇θ) where {T} size(madapter.Minv, 1) == 0 && (madapter.Minv = Diagonal(one.(θ))) return madapter.Minv end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1574
using LinearAlgebra """ Use the full covariance matrix of a moving average of samples as the mass matrix. This is similar to what is already done in Adaptive MH. # Fields - `Minv`: Inverse mass matrix as used in HMC, SGLD, GGMC, ... - `adapt_steps`: Number of adaptation steps. - `windowlength`: Lookback length for calculation of covariance. - `t`: Current step. - `kappa`: How much to shrink towards the identity. - `epsilon`: Small value to add to diagonal to avoid numerical instability. """ mutable struct FullCovMassAdapter{T} <: MassAdapter Minv::AbstractMatrix{T} adapt_steps::Int windowlength::Int t::Int kappa::T epsilon::T end function FullCovMassAdapter( adapt_steps::Int, windowlength::Int; Minv::AbstractMatrix=Matrix(undef, 0, 0), kappa::T=0.5f0, epsilon=1.0f-6 ) where {T} size(Minv, 1) == 0 && (Minv = Matrix{T}(undef, 0, 0)) return FullCovMassAdapter(Minv, adapt_steps, windowlength, 1, kappa, epsilon) end function (madapter::FullCovMassAdapter{T})( s::MCMCState, θ::AbstractVector{T}, bnn::BNN, ∇θ ) where {T} madapter.t == 1 && size(madapter.Minv, 1) == 0 && (madapter.Minv = diagm(one.(θ))) madapter.t > madapter.adapt_steps && return madapter.Minv madapter.windowlength > s.nsampled && return madapter.Minv madapter.Minv = (T(1) - madapter.kappa) * cov(permutedims(s.samples[:, s.nsampled-madapter.windowlength+1:s.nsampled])) + madapter.kappa * I madapter.Minv = madapter.Minv + madapter.epsilon * I madapter.t += 1 return madapter.Minv end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1215
""" Use RMSProp as a precondition/mass matrix adapter. This was proposed in Li, C., Chen, C., Carlson, D., & Carin, L. (2016, February). Preconditioned stochastic gradient Langevin dynamics for deep neural networks. In Thirtieth AAAI Conference on Artificial Intelligence for the use in SGLD and related methods. """ mutable struct RMSPropMassAdapter <: MassAdapter Minv::AbstractMatrix V::AbstractVector λ α t::Int adapt_steps::Int end function RMSPropMassAdapter( adapt_steps=1000; Minv::AbstractMatrix=Matrix(undef, 0, 0), λ=1.0f-5, α=0.99f0 ) return RMSPropMassAdapter(Minv, Vector[], λ, α, 1, adapt_steps) end function (madapter::RMSPropMassAdapter)( s::MCMCState, θ::AbstractVector{T}, bnn::BNN, ∇θ ) where {T} madapter.t > madapter.adapt_steps && return madapter.Minv madapter.t == 1 && size(madapter.Minv, 1) == 0 && (madapter.Minv = Diagonal(one.(θ))) madapter.t == 1 && (madapter.V = one.(θ)) v, g = ∇θ(θ) g ./= norm(g) madapter.V = madapter.α * madapter.V + (1 - madapter.α) * g .* g madapter.Minv = Diagonal(T(1) ./ (madapter.λ .+ sqrt.(madapter.V))) madapter.t += 1 return madapter.Minv end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
629
""" Adapt the stepsize of MCMC algorithms. # Implentation Details ## Mandatory Fields - `l::Number` The stepsize. Will be used by the sampler. ## Mandatory Functions - `(sadapter::StepsizeAdapter)(s::MCMCState, mh_probability::Number)` Every stepsize adapter must be callable with arguments, being the sampler itself and the Metropolis-Hastings acceptance probability. The method must return the new stepsize. """ abstract type StepsizeAdapter end function (sadater::StepsizeAdapter)(s::MCMCState, mh_probability) error("$(typeof(sadapter)) is not callable. Please read the documentation of StepsizeAdapter.") end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
177
""" Use a contant stepsize. """ struct ConstantStepsize{T} <: StepsizeAdapter l::T end (sadapter::ConstantStepsize{T})(s::MCMCState, mh_probability) where {T} = sadapter.l
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1512
""" Use the Dual Average method to tune the stepsize. The use of the Dual Average method was proposed in: Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15, 31. """ mutable struct DualAveragingStepSize{T} <: StepsizeAdapter l::T mu::T target_accept::T gamma::T t::Int kappa::T error_sum::T log_averaged_step::T adapt_steps::Int end function DualAveragingStepSize( initial_step_size::T; target_accept=T(0.65), gamma=T(0.05), t0=10, kappa=T(0.75), adapt_steps=1000 ) where {T} return DualAveragingStepSize( initial_step_size, log(10 * initial_step_size), target_accept, gamma, t0, kappa, T(0), T(0), adapt_steps ) end function (sadapter::DualAveragingStepSize{T})(s::MCMCState, mh_probability) where {T} if sadapter.t > sadapter.adapt_steps s.l = exp(sadapter.log_averaged_step) return exp(sadapter.log_averaged_step) end mh_probability = T(mh_probability) sadapter.error_sum += sadapter.target_accept - mh_probability log_step = sadapter.mu - sadapter.error_sum / sqrt(sadapter.t * sadapter.gamma) eta = sadapter.t^(-sadapter.kappa) sadapter.log_averaged_step = eta * log_step + (1 - eta) * sadapter.log_averaged_step sadapter.t += 1 sadapter.l = exp(log_step) return exp(log_step) end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2394
using Flux using ProgressMeter """ Find the mode of a BNN. Find the mode of a BNN using `optimiser`. Each `optimiser` must have implemented a function `step!(optimiser, θ, ∇θ)` which makes one optimisation step given gradient function ∇θ(θ) and current parameter vector θ. The function must return θ as the first return value and a flag `has_converged` indicating whether the optimisation procedure should be stopped. """ abstract type BNNModeFinder end step!(mf::BNNModeFinder, θ::AbstractVector, ∇θ::Function) = error("$(typeof(mf)) has not implemented the step! function. Please see the documentation for BNNModeFinder") """ find_mode(bnn::BNN, batchsize::Int, epochs::Int, optimiser::BNNModeFinder) Find the mode of a BNN. # Arguments - `bnn::BNN`: A Bayesian Neural Network formed using `BNN`. - `batchsize::Int`: Batchsize used for stochastic gradients. - `epochs::Int`: Number of epochs to run for. - `optimiser::BNNModeFinder`: An optimiser. # Keyword Arguments - `shuffle::Bool=true`: Should data be shuffled after each epoch? - `partial::Bool=true`: Is it allowed to use a batch that is smaller than `batchsize`? - `showprogress::Bool=true`: Show a progress bar? """ function find_mode( bnn::BNN, batchsize::Int, epochs::Int, optimiser::BNNModeFinder; shuffle=true, partial=true, showprogress=true ) if !partial && !shuffle @warn """shuffle and partial should not be both false unless the data is perfectly divided by the batchsize. If this is not the case, some data would never be considered""" end θnet, θhyper, θlike = bnn.init() θ = vcat(θnet, θhyper, θlike) batcher = Flux.Data.DataLoader( (x=bnn.x, y=bnn.y), batchsize=batchsize, shuffle=shuffle, partial=partial ) num_batches = length(batcher) prog = Progress( num_batches * epochs; desc="Finding Mode...", enabled=showprogress, showspeed=true ) ∇θ(θ, x, y) = ∇loglikeprior(bnn, θ, x, y; num_batches=num_batches) for e = 1:epochs for (x, y) in batcher θ, has_converged = step!(optimiser, θ, θ -> ∇θ(θ, x, y)) if has_converged @info "Converged!" return θ end next!(prog) end end @info "Failed to converge." return θ end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1416
""" FluxModeFinder(bnn::BNN, opt::O; windowlength = 100, ϵ = 1e-6) where {O<:Flux.Optimise.AbstractOptimiser} Use one of Flux optimisers to find the mode. Keep track of changes in θ over a window of `windowlegnth` and report convergence if the maximum change over the current window is smaller than ϵ. """ mutable struct FluxModeFinder{B,O,T} <: BNNModeFinder bnn::B opt::O windowlength::Int window::Vector{T} prevθ::Vector{T} ϵ::T i::Int end function FluxModeFinder( bnn::BNN, opt::O; windowlength=100, ϵ=1e-6 ) where {O<:Flux.Optimise.AbstractOptimiser} T = eltype(bnn.like.nc.θ) ϵ = T(ϵ) window = fill(T(-Inf), windowlength) prevθ = fill(T(Inf), bnn.num_total_params) i = 1 return FluxModeFinder(bnn, opt, windowlength, window, prevθ, ϵ, i) end function step!(fmf::FluxModeFinder, θ::AbstractVector{T}, ∇θ::Function) where {T} # Checking for convergence if fmf.i == 1 maxchange = maximum(abs, fmf.window) if maxchange <= fmf.ϵ return θ, true end end v, g = ∇θ(θ) maxchange = maximum(abs, fmf.prevθ - θ) fmf.window[fmf.i] = maxchange fmf.prevθ = copy(θ) fmf.i = fmf.i == fmf.windowlength ? 1 : fmf.i + 1 # We need maximisation while flux does by default minimisation. # So we negate the gradient. Flux.update!(fmf.opt, θ, -g) return θ, false end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2298
################################################################################ # ADVI for BayesFlux # FIXME: Something goes wrong using ADVI and empty vectors (θhyper) ################################################################################ using AdvancedVI, DistributionsAD using ProgressMeter """ advi(bnn::BNN, samples_per_step::Int, maxiters::Int, args...; kwargs...) Estimate a BNN using Automatic Differentiation Variational Inference (ADVI). # Uses - Uses ADVI as implemented in AdvancedVI.jl # Arguments - `bnn`: A Bayesian Neural Network - `samples_per_step`: Samples per step to be used to approximate expectation. - `maxiters`: Number of iteratios for which ADVI should run. ADVI does not currently include convergence criteria. As such, the algorithm will run for the full `maxiters` iterations - `args...`: Other argumetns to be passed on to advi - `kwargs...`: Other arguments to be passed on to advi """ function advi(bnn::BNN, samples_per_step::Int, maxiters::Int, args...; kwargs...) getq(θ) = MvNormal(θ[1:bnn.num_total_params], exp.(θ[bnn.num_total_params+1:end])) return advi(bnn, getq, samples_per_step, maxiters, args...; kwargs...) end """ advi(bnn::BNN, getq::Function, samples_per_step::Int, maxiters::Int; showprogress = true) Estimate a BNN using Automatic Differentiation Variational Inference (ADVI). # Uses - Uses ADVI as implemented in AdvancedVI.jl # Arguments - `bnn`: A Bayesian Neural Network - `getq`: A function that takes a vector and returns the variational distribution. - `samples_per_step`: Samples per step to be used to approximate expectation. - `maxiters`: Number of iteratios for which ADVI should run. ADVI does not currently include convergence criteria. As such, the algorithm will run for the full `maxiters` iterations # Keyword Arguments - `showprogress = true`: Should progress be shown? """ function advi(bnn::BNN, getq::Function, samples_per_step::Int, maxiters::Int; showprogress=true) AdvancedVI.turnprogress(showprogress) lπ(θ) = loglikeprior(bnn, θ, bnn.x, bnn.y) θnet, θhyper, θlike = bnn.init() initθ = vcat(θnet, θhyper, θlike) AdvancedVI.setadbackend(:zygote) advi = ADVI(samples_per_step, maxiters) q = AdvancedVI.vi(lπ, advi, getq, initθ) return q end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3218
using StatsFuns using Random, Distributions using ProgressMeter function loss_bbb(bnn::B, ψ::AbstractVector{T}, x::Union{Vector{Matrix{T}},Matrix{T},Array{T,3}}, y::Union{Vector{T},Matrix{T}}; num_batches=T(1)) where {B<:BNN,T} n = Int(length(ψ) / 2) μ = ψ[1:n] σ = log1pexp.(ψ[n+1:end]) ϵ = randn(T, n) θ = μ .+ σ .* ϵ return logpdf(MvNormal(μ, σ), θ) - loglikeprior(bnn, θ, x, y; num_batches=num_batches) end function ∇bbb(bnn::B, ψ::AbstractVector{T}, x::Union{Vector{Matrix{T}},Matrix{T},Array{T,3}}, y::Union{Vector{T},Matrix{T}}; num_batches=T(1)) where {B<:BNN,T} return Zygote.gradient(ψ -> loss_bbb(bnn, ψ, x, y; num_batches=num_batches), ψ)[1] end """ bbb(args...; kwargs...) Use Bayes By Backprop to find Variational Approximation to BNN. This was proposed in Blundell, C., Cornebise, J., Kavukcuoglu, K., & Wierstra, D. (2015, June). Weight uncertainty in neural network. In International conference on machine learning (pp. 1613-1622). PMLR. # Arguments - `bnn::BNN`: The Bayesian NN - `batchsize::Int`: Batchsize - `epochs::Int`: Epochs # Keyword Arguments - `mc_samples::Int=1`: Over how many gradients should be averaged? - `shuffle::Bool=true`: Should observations be shuffled after each epoch? - `partial::Bool=true`: Can the last batch be smaller than batchsize? - `showprogress::Bool=true`: Show progress bar? - `opt=Flux.ADAM()`: Must be an optimiser of type Flux.Optimiser - `n_samples_convergence::Int=10`: After each epoch the loss is calculated and kept track of using an average of `n_samples_convergence` samples. """ function bbb( bnn::BNN, batchsize::Int, epochs::Int; mc_samples=1, shuffle=true, partial=true, showprogress=true, opt=Flux.ADAM(), n_samples_convergence=10 ) T = eltype(bnn.like.nc.θ) if !partial && !shuffle @warn """shuffle and partial should not be both false unless the data is perfectly divided by the batchsize. If this is not the case, some data would never be considered""" end θnet, θhyper, θlike = bnn.init() initμ = vcat(θnet, θhyper, θlike) initσ = ones(T, length(initμ)) ψ = vcat(initμ, initσ) batcher = Flux.Data.DataLoader((x=bnn.x, y=bnn.y), batchsize=batchsize, shuffle=shuffle, partial=partial) num_batches = length(batcher) prog = Progress(num_batches * epochs; enabled=showprogress, desc="BBB...", showspeed=true) ∇ψ(ψ, x, y) = ∇bbb(bnn, ψ, x, y; num_batches=num_batches) ψs = Array{T}(undef, length(ψ), epochs) losses = Array{T}(undef, epochs) gs = Array{T}(undef, length(ψ), mc_samples) for e = 1:epochs for (x, y) in batcher # Threads.@threads for s=1:mc_samples @simd for s = 1:mc_samples gs[:, s] = ∇ψ(ψ, x, y) end g = vec(mean(gs; dims=2)) Flux.update!(opt, ψ, g) next!(prog) end ψs[:, e] = copy(ψ) losses[e] = mean([loss_bbb(bnn, ψ, bnn.x, bnn.y) for _ in 1:n_samples_convergence]) end n = bnn.num_total_params μ = ψ[1:n] σ = log1pexp.(ψ[(n+1):end]) return MvNormal(μ, σ), ψs, losses end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
705
""" abstract type BNNInitialiser end To initialise BNNs, BNNInitialisers are used. These must be callable and must return three vectors - `θnet` the initial values for the network parameters - `θhyper` the initial values for any hyperparameters introduced by the NetworkPrior - `θlike` the initial values for any extra parameters introduced by the likelihood # Implementation Every BNNInitialiser must be callable and must return the above three things: (init::BNNInitialiser)(rng::AbstractRNG) -> (θnet, θhyper, θlike) """ abstract type BNNInitialiser end (init::BNNInitialiser)() = error("The initialiser is not properly implemented. Please see the BNNInitialiser documentation.")
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
936
""" InitialiseAllSame(dist::D, like::BNNLikelihood, prior::NetworkPrior) Initialise all values by drawing from `dist` """ struct InitialiseAllSame{D<:Distributions.Distribution} <: BNNInitialiser length_θnet::Int length_hyper::Int length_like::Int type::Type dist::D end function InitialiseAllSame(dist::D, like::BNNLikelihood, prior::NetworkPrior) where {D} length_θnet = like.nc.num_params_network length_hyper = prior.num_params_hyper length_like = like.num_params_like type = eltype(like.nc.θ) return InitialiseAllSame(length_θnet, length_hyper, length_like, type, dist) end function (init::InitialiseAllSame{D})(rng::AbstractRNG=Random.GLOBAL_RNG) where {D} θnet = rand(rng, init.dist, init.length_θnet) θhyper = rand(rng, init.dist, init.length_hyper) θlike = rand(rng, init.dist, init.length_like) return init.type.(θnet), init.type.(θhyper), init.type.(θlike) end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
932
################################################################################ # Layer implementations are documented in implementation-layer.md ################################################################################ using Flux, Random, Distributions using Optimisers using Bijectors using Parameters ################################################################################ # Dense: standard ################################################################################ function destruct(cell::Flux.Dense) @unpack weight, bias, σ = cell θ = vcat(vec(weight), vec(bias)) function re(θ::AbstractVector) s = 1 pweight = length(weight) new_weight = reshape(θ[s:s+pweight-1], size(weight)) s += pweight pbias = length(bias) new_bias = reshape(θ[s:s+pbias-1], size(bias)) return Flux.Dense(new_weight, new_bias, σ) end return θ, re end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2505
################################################################################ # Layer implementations are documented in implementation-layer.md ################################################################################ using Flux, Random, Distributions using Optimisers using Bijectors using Parameters ################################################################################ # RNN ################################################################################ function destruct(cell::Flux.Recur{R}) where {R<:Flux.RNNCell} @unpack σ, Wi, Wh, b, state0 = cell.cell # θ = vcat(vec(Wi), vec(Wh), vec(b), vec(state0)) θ = vcat(vec(Wi), vec(Wh), vec(b)) function re(θ::Vector{T}) where {T} s = 1 pWi = length(Wi) new_Wi = reshape(θ[s:s+pWi-1], size(Wi)) s += pWi pWh = length(Wh) new_Wh = reshape(θ[s:s+pWh-1], size(Wh)) s += pWh pb = length(b) new_b = reshape(θ[s:s+pb-1], size(b)) s += pb # pstate0 = length(state0) # new_state0 = reshape(θ[s:s+pstate0-1], size(state0)) new_state0 = zeros(T, size(state0)) return Flux.Recur(Flux.RNNCell(σ, new_Wi, new_Wh, new_b, new_state0)) end return θ, re end ################################################################################ # LSTM ################################################################################ function destruct(cell::Flux.Recur{R}) where {R<:Flux.LSTMCell} @unpack Wi, Wh, b, state0 = cell.cell # state 0 has two states, one for h and one for c # see wikipedia article # θ = vcat(vec(Wi), vec(Wh), vec(b), vec(state0[1]), vec(state0[2])) θ = vcat(vec(Wi), vec(Wh), vec(b)) function re(θ::Vector{T}) where {T} s = 1 pWi = length(Wi) new_Wi = reshape(θ[s:s+pWi-1], size(Wi)) s += pWi pWh = length(Wh) new_Wh = reshape(θ[s:s+pWh-1], size(Wh)) s += pWh pb = length(b) new_b = reshape(θ[s:s+pb-1], size(b)) # s += pb # pstate01 = length(state0[1]) # new_state01 = reshape(θ[s:s+pstate01-1], size(state0[1])) new_state01 = zeros(T, size(state0[1])) # s += pstate01 # pstate02 = length(state0[2]) # new_state02 = reshape(θ[s:s+pstate02-1], size(state0[2])) new_state02 = zeros(T, size(state0[2])) return Flux.Recur(Flux.LSTMCell(new_Wi, new_Wh, new_b, (new_state01, new_state02))) end return θ, re end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1523
""" abstract type BNNLikelihood end Every likelihood must be a subtype of BNNLikelihood and must implement at least the following fields: - `num_params_like`: The number of additional parameters introduced for which inference will be done (i.e. σ for a Gaussian but not ν for a T-Dist if df is not inferred) - `nc`: A NetConstructor Every BNNLikelihood must be callable in the following way (l::BNNLikelihood)(x, y, θnet, θlike) - `x` either all data or a minibatch - `y` either all data or a minibatch - `θnet` are the network parameter - `θlike` are the likelihood parameters. If no additional parameters were introduced, this will be an empty array Every BNNLikelihood must also implement a posterior_predict method which should draw from the posterior predictive given network parameters and likelihood parameters. posterior_predict(l::BNNLikelihood, x, θnet, θlike) - `l` the BNNLikelihood - `x` the input data - `θnet` network parameters - `θlike` likelihood parameters """ abstract type BNNLikelihood end function (l::BNNLikelihood)( x::Union{Vector{Matrix{T}},Matrix{T},Array{T,3}}, y::Union{Vector{T},Matrix{T}}, θnet::AbstractVector, θlike::AbstractVector ) where {T} error("Seems like your likelihood is not callable. Please see the documentation for BNNLikelihood.") end posterior_predict(l::BNNLikelihood, x, θnet, θlike) = error("Seems like your likelihood did not implement a posterior_predict method. Please see the documentation for BNNLikelihood.")
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3375
using Distributions using Bijectors ################################################################################ # Normal ################################################################################ """ FeedforwardNormal(nc::NetConstructor{T, F}, prior_σ::D) where {T, F, D<:Distribution} Use a Gaussian/Normal likelihood for a Feedforward architecture with a single output. Assumes is a single output. Thus, the last layer must have output size one. # Arguments - `nc`: obtained using [`destruct`](@ref) - `prior_σ`: a prior distribution for the standard deviation """ struct FeedforwardNormal{T,F,D<:Distributions.Distribution} <: BNNLikelihood num_params_like::Int nc::NetConstructor{T,F} prior_σ::D end function FeedforwardNormal(nc::NetConstructor{T,F}, prior_σ::D) where {T,F,D<:Distributions.Distribution} return FeedforwardNormal(1, nc, prior_σ) end function (l::FeedforwardNormal{T,F,D})(x::Matrix{T}, y::Vector{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec(net(x)) tdist = transformed(l.prior_σ) sigma = invlink(l.prior_σ, θlike[1]) n = length(y) # Using reparameterised likelihood # Usually results in faster gradients return logpdf(MvNormal(zeros(n), I), (y - yhat) ./ sigma) - n * log(sigma) + logpdf(tdist, θlike[1]) end function posterior_predict(l::FeedforwardNormal{T,F,D}, x::Matrix{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec(net(x)) sigma = invlink(l.prior_σ, θlike[1]) ypp = rand(MvNormal(yhat, sigma^2 * I)) return ypp end ################################################################################ # T Distribution fixed df ################################################################################ """ FeedforwardTDist(nc::NetConstructor{T, F}, prior_σ::D, ν::T) where {T, F, D} Use a Student-T likelihood for a Feedforward architecture with a single output and known degress of freedom. Assumes is a single output. Thus, the last layer must have output size one. # Arguments - `nc`: obtained using [`destruct`](@ref) - `prior_σ`: a prior distribution for the standard deviation - `ν`: degrees of freedom """ struct FeedforwardTDist{T,F,D<:Distributions.Distribution} <: BNNLikelihood num_params_like::Int nc::NetConstructor{T,F} prior_σ::D ν::T end function FeedforwardTDist(nc::NetConstructor{T,F}, prior_σ::D, ν::T) where {T,F,D} return FeedforwardTDist(1, nc, prior_σ, ν) end function (l::FeedforwardTDist{T,F,D})(x::Matrix{T}, y::Vector{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec(net(x)) tdist = transformed(l.prior_σ) sigma = invlink(l.prior_σ, θlike[1]) n = length(y) return sum(logpdf.(TDist(l.ν), (y - yhat) ./ sigma)) - n * log(sigma) + logpdf(tdist, θlike[1]) end function posterior_predict(l::FeedforwardTDist{T,F,D}, x::Matrix{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec(net(x)) sigma = invlink(l.prior_σ, θlike[1]) n = length(yhat) ypp = sigma * rand(TDist(l.ν), n) + yhat return ypp end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3516
using Distributions using LinearAlgebra ############################################################################### # Sequence to one Normal ################################################################################ """ SeqToOneNormal(nc::NetConstructor{T, F}, prior_σ::D) where {T, F, D<:Distribution} Use a Gaussian/Normal likelihood for a Seq-to-One architecture with a single output. Assumes is a single output. Thus, the last layer must have output size one. # Arguments - `nc`: obtained using [`destruct`](@ref) - `prior_σ`: a prior distribution for the standard deviation """ struct SeqToOneNormal{T,F,D<:Distributions.Distribution} <: BNNLikelihood num_params_like::Int nc::NetConstructor{T,F} prior_σ::D end function SeqToOneNormal(nc::NetConstructor{T,F}, prior_σ::D) where {T,F,D<:Distributions.Distribution} return SeqToOneNormal(1, nc, prior_σ) end function (l::SeqToOneNormal{T,F,D})(x::Array{T,3}, y::Vector{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec([net(xx) for xx in eachslice(x; dims=1)][end]) tdist = transformed(l.prior_σ) sigma = invlink(l.prior_σ, θlike[1]) n = length(y) # Using reparameterised likelihood # Usually results in faster gradients return logpdf(MvNormal(zeros(n), I), (y - yhat) ./ sigma) - n * log(sigma) + logpdf(tdist, θlike[1]) end function posterior_predict(l::SeqToOneNormal{T,F,D}, x::Array{T,3}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec([net(xx) for xx in eachslice(x; dims=1)][end]) sigma = invlink(l.prior_σ, θlike[1]) ypp = rand(MvNormal(yhat, sigma^2 * I)) return ypp end ################################################################################ # Sequence to one TDIST ################################################################################ """ SeqToOneTDist(nc::NetConstructor{T, F}, prior_σ::D, ν::T) where {T, F, D} Use a Student-T likelihood for a Seq-to-One architecture with a single output and known degress of freedom. Assumes is a single output. Thus, the last layer must have output size one. # Arguments - `nc`: obtained using [`destruct`](@ref) - `prior_σ`: a prior distribution for the standard deviation - `ν`: degrees of freedom """ struct SeqToOneTDist{T,F,D<:Distributions.Distribution} <: BNNLikelihood num_params_like::Int nc::NetConstructor{T,F} prior_σ::D ν::T end function SeqToOneTDist(nc::NetConstructor{T,F}, prior_σ::D, ν::T) where {T,F,D} return SeqToOneTDist(1, nc, prior_σ, ν) end function (l::SeqToOneTDist{T,F,D})(x::Array{T,3}, y::Vector{T}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec([net(xx) for xx in eachslice(x; dims=1)][end]) tdist = transformed(l.prior_σ) sigma = invlink(l.prior_σ, θlike[1]) n = length(y) return sum(logpdf.(TDist(l.ν), (y - yhat) ./ sigma)) - n * log(sigma) + logpdf(tdist, θlike[1]) end function posterior_predict(l::SeqToOneTDist{T,F,D}, x::Array{T,3}, θnet::AbstractVector, θlike::AbstractVector) where {T,F,D} θnet = T.(θnet) θlike = T.(θlike) net = l.nc(θnet) yhat = vec([net(xx) for xx in eachslice(x; dims=1)][end]) sigma = invlink(l.prior_σ, θlike[1]) n = length(yhat) ypp = sigma * rand(TDist(l.ν), n) + yhat return ypp end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3821
using Flux, Distributions, Random using Zygote struct BNN{Tx,Ty,L,P,I} x::Tx y::Ty like::L prior::P init::I start_θnet::Int start_θhyper::Int start_θlike::Int num_total_params::Int end """ BNN(x, y, like::BNNLikelihood, prior::NetworkPrior, init::BNNInitialiser) Create a Bayesian Neural Network. # Arguments - `x`: Explanatory data - `y`: Dependent variables - `like`: A likelihood - `prior`: A prior on network parameters - `init`: An initilialiser """ function BNN(x, y, like::BNNLikelihood, prior::NetworkPrior, init::BNNInitialiser) start_θnet = 1 start_θhyper = start_θnet + like.nc.num_params_network start_θlike = prior.num_params_hyper == 0 ? start_θhyper : start_θhyper + prior.num_params_hyper - 1 num_total_params = like.nc.num_params_network + like.num_params_like + prior.num_params_hyper return BNN(x, y, like, prior, init, start_θnet, start_θhyper, start_θlike, num_total_params) end function split_params(bnn::B, θ::Vector{T}) where {B<:BNN,T} θnet = @view θ[1:(bnn.start_θhyper-1)] θhyper = bnn.prior.num_params_hyper == 0 ? eltype(θ)[] : @view θ[bnn.start_θhyper:(bnn.start_θlike-1)] θlike = @view θ[bnn.start_θlike:end] return θnet, θhyper, θlike end """ Obtain the log of the unnormalised posterior. """ function loglikeprior(bnn::B, θ::Vector{T}, x::Union{Vector{Matrix{T}},Matrix{T},Array{T,3}}, y::Union{Vector{T},Matrix{T}}; num_batches=T(1)) where {B<:BNN,T} θnet, θhyper, θlike = split_params(bnn, θ) return num_batches * bnn.like(x, y, θnet, θlike) + bnn.prior(θnet, θhyper) end """ Obtain the derivative of the unnormalised log posterior. """ function ∇loglikeprior(bnn::B, θ::Vector{T}, x::Union{Vector{Matrix{T}},Matrix{T},Array{T,3}}, y::Union{Vector{T},Matrix{T}}; num_batches=T(1)) where {B<:BNN,T} llp(θ) = loglikeprior(bnn, θ, x, y; num_batches=num_batches) v, g = Zygote.withgradient(llp, θ) return v, g[1] end function clip_gradient_value!(g, maxval=15) maxabs_g_val = maximum(abs.(g)) if maxabs_g_val > maxval g .= maxval / maxabs_g_val .* g end return g end """ sample_prior_predictive(bnn::BNN, predict::Function, n::Int = 1; Samples from the prior predictive. # Arguments - `bnn` a BNN - `predict` a function taking a network and returning a vector of predictions - `n` number of samples # Optional Arguments - `rng` a RNG """ function sample_prior_predictive(bnn::BNN, predict::Function, n::Int=1; rng::Random.AbstractRNG=Random.GLOBAL_RNG) prior = bnn.prior θnets = [sample_prior(prior, rng) for i = 1:n] nets = [prior.nc(θ) for θ in θnets] ys = [predict(net) for net in nets] return ys end """ get_posterior_networks(bnn::BNN, ch::AbstractMatrix{T}) where {T} Get the networks corresponding to posterior draws. # Arguments - `bnn` a BNN - `ch` A Matrix of draws (columns are θ) """ function get_posterior_networks(bnn::BNN, ch::AbstractMatrix{T}) where {T} nets = [bnn.prior.nc(Float32.(split_params(bnn, ch[:, i])[1])) for i = 1:size(ch, 2)] return nets end """ sample_posterior_predict(bnn::BNN, ch::AbstractMatrix{T}; x = bnn.x) Sample from the posterior predictive distribution. # Arguments - `bnn`: a Bayesian Neural Network - `ch`: draws from the posterior. These should be either obtained using [`mcmc`](@ref) or [`bbb`](@ref) - `x`: explanatory variables. Default is to use the training data. """ function sample_posterior_predict(bnn::BNN, ch::AbstractMatrix{T}; x=bnn.x) where {T} θnets = [T.(split_params(bnn, ch[:, i])[1]) for i = 1:size(ch, 2)] θlikes = [T.(split_params(bnn, ch[:, i])[3]) for i = 1:size(ch, 2)] ys = reduce(hcat, [posterior_predict(bnn.like, x, θnet, θlike) for (θnet, θlike) in zip(θnets, θlikes)]) return ys end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1716
""" NetConstructor{T, F} Used to construct a network from a vector. The `NetConstructor` constains all important information to construct a network like the original network from a given vector. # Fields - `num_params_net`: Number of network parameters - `θ`: Vector of network parameters of the original network - `starts`: Vector containing the starting points of each layer in θ - `ends`: Vector containing the end points of each layer in θ - `reconstructors`: Vector containing the reconstruction functions for each layer """ struct NetConstructor{T,F} num_params_network::Int θ::Vector{T} starts::Vector{Int} ends::Vector{Int} reconstructors::Vector{F} end function (nc::NetConstructor{T})(θ::Vector{T}) where {T} layers = [re(θ[s:e]) for (re, s, e) in zip(nc.reconstructors, nc.starts, nc.ends)] return Flux.Chain(layers...) end """ destruct(net::Flux.Chain{T}) where {T} Destruct a network Given a `Flux.Chain` network, destruct it and create a NetConstructor. Each layer type must implement a destruct method taking the layer and returning a vector containing the original layer parameters, and a function that given a vector of the right length constructs a layer like the original using the parameters given in the vector """ function destruct(net::Flux.Chain{T}) where {T} θre = [destruct(layer) for layer in net] θ = vcat([item[1] for item in θre]...) res = [item[2] for item in θre] s = ones(Int, length(θre)) e = similar(s) for i in eachindex(θre) e[i] = s[i] + length(θre[i][1]) - 1 if (i < length(θre)) s[i+1] = e[i] + 1 end end return NetConstructor(length(θ), θ, s, e, res) end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
453
# Methods used for posterior analysis and predictions function posterior_predict(bnn::BNN, samples::Matrix{T}; kwargs...) where {T<:Real} return posterior_predict(bnn, bnn.loglikelihood, samples; kwargs...) end function posterior_predict(bnn::BNN, samples::Array{T,3}; kwargs...) where {T<:Real} ppreds = [posterior_predict(bnn, samples[:, :, i]; kwargs...) for i = 1:size(samples, 3)] ppreds = cat(ppreds...; dims=3) return ppreds end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1113
""" abstract type NetworkPrior end All priors over the network parameters are subtypes of NetworkPrior. # Required Fields - `num_params_hyper`: Number of hyper priors (only those that should be inferred) - `nc::NetConstructor`: NetConstructor # Required implementations Each NetworkPrior must be callable in the form of (np::NetworkPrior)(θnet, θhyper) - `θnet` is a vector of network parameters - `θhyper` is a vector of hyper parameters The return value must be the logprior including all hyper-priors. Each NetworkPrior must also implement a sample function returning a vector `θnet` of network parameters drawn from the prior. sample_prior(np::NetworkPrior)(rng::AbstractRNG) """ abstract type NetworkPrior end (np::NetworkPrior)(θnet::AbstractVector, θhyper::AbstractVector) = error("Seems like your network prior is not implemented correctly. Please consult the documentation for NetworkPrior.") sample_prior(np::NetworkPrior, rng::Random.AbstractRNG) = error("Seems like your network prior is not implemented correctly. Please consult the documentation for NetworkPrior.")
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
956
# Very simple prior. # θ_i ∼ Normal(0, σ0) for all network parameters θ_i using Distributions using Random struct GaussianPrior{T,F} <: NetworkPrior num_params_hyper::Int nc::NetConstructor{T,F} σ0::T end """ Use a Gaussian prior for all network parameters. This means that we do not allow for any correlations in the network parameters in the prior. # Arguments - `nc`: obtained using [`destruct`](@ref) - `σ0`: standard deviation of prior """ function GaussianPrior(nc::NetConstructor{T,F}, σ0::T=T(1.0)) where {T,F} return GaussianPrior(0, nc, σ0) end function (gp::GaussianPrior{T,F})(θnet::AbstractVector{T}, θhyper::AbstractVector{T}) where {T,F} n = length(θnet) return logpdf(MvNormal(zeros(T, n), gp.σ0^2 * I), θnet) end function sample_prior(gp::GaussianPrior{T,F}, rng::AbstractRNG=Random.GLOBAL_RNG) where {T,F} θnet = rand(rng, MvNormal(zeros(T, gp.nc.num_params_network), gp.σ0^2 * I)) return θnet end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1406
using Random using StatsBase using LinearAlgebra """ MixtureScalePrior(nc::NetConstructor{T, F}, σ1::T, σ2::T, μ1::T) Scale mixture of Gaussians # Fields - `num_params_hyper::Int=0`: Number of hyper priors - `nc::NetConstructor`: NetConstructor object - `σ1`: Standard deviation of first Gaussian - `σ2`: Standard deviation of second Gaussian - `π1`: Weight/Probability of first Gaussian - `π2`: Weight/Probability of second Gaussian (`1-π1`) """ struct MixtureScalePrior{T,F} <: NetworkPrior num_params_hyper::Int nc::NetConstructor{T,F} σ1::T σ2::T π1::T π2::T end function MixtureScalePrior(nc::NetConstructor{T,F}, σ1::T, σ2::T, μ1::T) where {T,F} return MixtureScalePrior(0, nc, σ1, σ2, μ1, T(1) - μ1) end function (msp::MixtureScalePrior{T,F})(θnet::AbstractVector{T}, θhyper::AbstractVector{T}) where {T,F} n = length(θnet) return msp.π1 * logpdf(MvNormal(zeros(T, n), msp.σ1^2 * I), θnet) + msp.π2 * logpdf(MvNormal(zeros(T, n), msp.σ2^2 * I), θnet) end function sample_prior(msp::MixtureScalePrior{T,F}, rng::AbstractRNG=Random.GLOBAL_RNG) where {T,F} n = msp.nc.num_params_network θnet1 = rand(rng, MvNormal(zeros(T, n), msp.σ1^2 * I)) θnet2 = rand(rng, MvNormal(zeros(T, n), msp.σ2^2 * I)) take_1 = StatsBase.sample(0:1, StatsBase.ProbabilityWeights([msp.π2, msp.π1]), n) return take_1 .* θnet1 .+ (T(1) .- take_1) .* θnet2 end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
372
# Stochastic Search Variable Selection # TODO: Implement this # George, E. I., Sun, D., & Ni, S. (2008). Bayesian stochastic search for VAR # model restrictions. Journal of Econometrics, 142(1), 553-580. # https://mbjoseph.github.io/posts/2018-12-27-stochastic-search-variable-selection-in-jags/ # http://www-stat.wharton.upenn.edu/~edgeorge/Research_papers/fastN96.pdf
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
182
using LinearAlgebra """ Clip the norm of the gradient. """ function clip_gradient!(g; maxnorm=5.0f0) ng = norm(g) g .= ng > maxnorm ? maxnorm .* g ./ ng : g return g end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
686
""" make_rnn_tensor(m::Matrix{T}, seq_to_one_length = 10) where {T} Create a Tensor used for RNNs Given an input matrix of dimensions timesteps×features transform it into a Tensor of dimension timesteps×features×sequences where the sequences are overlapping subsequences of length `seq_to_one_length` of the orignal `timesteps` long sequence """ function make_rnn_tensor(m::Matrix{T}, seq_to_one_length=10) where {T} nfeatures = size(m, 2) nsequences = size(m, 1) - seq_to_one_length + 1 tensor = Array{T}(undef, seq_to_one_length, nfeatures, nsequences) for i = 1:nsequences tensor[:, :, i] = m[i:i+seq_to_one_length-1, :] end return tensor end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
682
using Flux, BayesFlux using Random, Distributions using ReTest @testset "ADVI" begin @testset "Linear Regression" begin k = 5 n = 100_000 x = randn(Float32, k, n) β = randn(Float32, k) y = x' * β + 0.1f0 * randn(Float32, n) net = Chain(Dense(5, 1)) nc = destruct(net) sigma_prior = Gamma(2.0f0, 0.5f0) like = FeedforwardNormal(nc, sigma_prior) prior = GaussianPrior(nc, 10.0f0) init = InitialiseAllSame(Normal(0.0f0, 1.0f0), like, prior) bnn = BNN(x, y, like, prior, init) # Using default variational distribution: MvNormal q = advi(bnn, 10, 10_000) end end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
2120
# Testing Adaptive MH using BayesFlux using Flux, Distributions, Random using LinearAlgebra function test_AMH_regression(; k=5, n=10_000) x = randn(Float32, k, n) β = randn(Float32, k) y = x' * β + 1.0f0 * randn(Float32, n) net = Chain(Dense(k, 1)) nc = destruct(net) sigma_prior = Gamma(2.0f0, 0.5f0) like = FeedforwardNormal(nc, sigma_prior) prior = GaussianPrior(nc, 10.0f0) init = InitialiseAllSame(Normal(0.0f0, 1.0f0), like, prior) bnn = BNN(x, y, like, prior, init) opt = FluxModeFinder(bnn, Flux.ADAM()) θmap = find_mode(bnn, 100, 10, opt; showprogress=false) sampler = AdaptiveMH(0.1f0 * diagm(one.(vcat(bnn.init()...))), 1000, 1.0f0, 1.0f-6) ch = mcmc(bnn, 1000, 20_000, sampler; showprogress=false, θstart=θmap) ch_short = ch[:, end-9999:end] θmean = mean(ch_short; dims=2) βhat = θmean[1:length(β)] # coefficient estimate test1 = maximum(abs, β - βhat) < 0.05 # Intercept test2 = abs(θmean[end-1]) < 0.05 # Variance test3 = 0.9f0 <= mean(exp.(ch_short[end, :])) <= 1.1f0 # Continue sampling test4 = BayesFlux.calculate_epochs(sampler, 100, 25_000; continue_sampling=true) == 50 ch_longer = mcmc(bnn, 1000, 25_000, sampler; continue_sampling=true) test5 = all(ch_longer[:, 1:20_000] .== ch) return [test1, test2, test3, test4, test5] end Random.seed!(6150533) @testset "AMH" begin @testset "Linear Regression" begin # Because GitHub Actions seem very slow and occasionally run out of # memory, we will decrease the number of tests if the tests are run on # GitHub actions. Hostnames on GH actions seem to always start with fv ntests = gethostname()[1:2] == "fv" ? 1 : 10 results = fill(false, ntests, 5) for i = 1:ntests results[i, :] = test_AMH_regression() end pct_pass = mean(results; dims=1) @test pct_pass[1] > 0.9 @test pct_pass[2] > 0.9 @test pct_pass[3] > 0.8 # variances are difficult to estimate @test pct_pass[4] == 1 @test pct_pass[5] == 1 end end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1458
using BayesFlux using Flux, Distributions, Random function test_BBB_regression(; k=5, n=10_000) x = randn(Float32, k, n) β = randn(Float32, k) y = x' * β + 1.0f0 * randn(Float32, n) net = Chain(Dense(5, 1)) nc = destruct(net) sigma_prior = InverseGamma(2.0f0, 0.5f0) like = FeedforwardNormal(nc, sigma_prior) prior = GaussianPrior(nc, 10.0f0) init = InitialiseAllSame(Normal(0.0f0, 1.0f0), like, prior) bnn = BNN(x, y, like, prior, init) q, params, losses = bbb(bnn, 1000, 1000; mc_samples=1, opt=Flux.RMSProp(), n_samples_convergence = 1) μ = mean(q) test1 = maximum(abs, β - μ[1:length(β)]) < 0.05 test2 = abs(μ[end-1]) < 0.05 test3 = 0.9f0 <= exp(μ[end]) <= 1.1f0 return [test1, test2, test3] end Random.seed!(6150533) @testset "BBB" begin @testset "Linear Regression" begin # Because GitHub Actions seem very slow and occasionally run out of # memory, we will decrease the number of tests if the tests are run on # GitHub actions. Hostnames on GH actions seem to always start with fv ntests = gethostname()[1:2] == "fv" ? 1 : 10 results = fill(false, ntests, 3) for i = 1:ntests results[i, :] = test_BBB_regression() end pct_pass = mean(results; dims=1) @test pct_pass[1] > 0.9 @test pct_pass[2] > 0.9 @test pct_pass[3] > 0.8 # variances are difficult to estimate end end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
3324
using BayesFlux using Flux, Distributions, Random using Bijectors using Zygote @testset "BNN" begin @testset "Split Parameter Vector" begin n = 1000 k = 5 x = randn(Float32, k, n) β = randn(Float32, k) y = x' * β + randn(Float32, n) net = Chain(Dense(5, 10, relu), Dense(10, 1)) nc = destruct(net) like = FeedforwardNormal(nc, Gamma(2.0, 2.0)) prior = GaussianPrior(nc, 10.0f0) init = InitialiseAllSame(Uniform(-0.5f0, 0.5f0), like, prior) bnn = BNN(x, y, like, prior, init) θ = vcat(init()...) θnet, θhyper, θlike = split_params(bnn, θ) @test length(θnet) == nc.num_params_network @test all(θnet .== θ[1:nc.num_params_network]) @test θnet == @view θ[1:nc.num_params_network] @test length(θhyper) == 0 @test length(θlike) == like.num_params_like @test θlike == @view θ[end:end] end @testset "Gradient" begin # This test is done using Float64 to avoid numerical differences # But we usually work with Float32 x = randn(2, 1) y = randn() net = Chain(Dense(randn(2, 2), randn(2), sigmoid), Dense(randn(1, 2), randn(1))) nc = destruct(net) like = FeedforwardNormal(nc, Gamma(2.0, 2.0)) prior = GaussianPrior(nc, 1.0) init = InitialiseAllSame(Normal(), like, prior) bnn = BNN(x, y, like, prior, init) θnet, θhyper, θlike = init() net = nc(θnet) # ∂yhat/∂θ yhat = net(x)[1] z = vec(net[1].weight * x + net[1].bias) a = vec(sigmoid.(z)) ∇W2 = reshape(vec(a), 1, 2) ∇b2 = 1.0 ∇a = vec(net[2].weight) ∇z = ∇a .* sigmoid.(z) .* (1.0 .- sigmoid.(z)) ∇W1r1 = reshape(∇z[1] .* vec(x), 1, 2) ∇W1r2 = reshape(∇z[2] .* vec(x), 1, 2) ∇W1 = vcat(∇W1r1, ∇W1r2) ∇b1 = ∇z # Comparing the above derivatives with those obtained from Zygote g = Zygote.gradient(() -> net(x)[1], Flux.params(net)) @test all(∇b1 .≈ g[net[1].bias]) @test all(∇W1 .≈ g[net[1].weight]) @test all(∇b2 .≈ g[net[2].bias]) @test all(∇W2 .≈ g[net[2].weight]) ∇yhat_θnet = vcat(vec(∇W1), vec(∇b1), vec(∇W2), ∇b2) # Guassian Likelihood contribution sigma = exp(θlike[1]) ∇like_sigma = -sigma^(-1) + sigma^(-3) * (y - yhat)^2 ∇like_θlike = ∇like_sigma * exp(θlike[1]) ∇like_yhat = sigma^(-2) * (y - yhat) ∇like_θnet = ∇like_yhat .* ∇yhat_θnet g = Zygote.gradient((yhat, sigma) -> logpdf(Normal(yhat, sigma), y), yhat, sigma) @test ∇like_yhat ≈ g[1] @test ∇like_sigma ≈ g[2] # σ prior contribution # We will trust Zygote here # TODO: change this tdist = transformed(Gamma(2.0, 2.0)) ∇prior_θlike = Zygote.gradient(θlike -> logpdf(tdist, θlike[1]), θlike)[1][1] # Priors for network parameters are standard normal ∇prior_θnet = -θnet # Final ∇θnet = ∇like_θnet .+ ∇prior_θnet ∇θlike = ∇like_θlike .+ ∇prior_θlike ∇θ = vcat(∇θnet, ∇θlike) # Comparing θ = vcat(θnet, θhyper, θlike) v, g = ∇loglikeprior(bnn, θ, x, [y]) @test all(∇θ .≈ g) end end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
6991
# Given a Flux.Chain object, we need to destruct the network. Returned should # be a NetConstructor object which must have fields `num_params_network`, `θ` # holding the current parameterisation and must be callable. Calling the # NetConstructor with a vector of length `num_params_network` then should return # a network of the same structure as the original network with the parameters # being taken from the input vector. using Flux using BayesFlux @testset "Destruct" begin @testset "destruct Dense" for in = 1:3 for out = 1:3 for act in [sigmoid, tanh, identity] @testset "Chain(Dense($in, $out))" begin net = Chain(Dense(in, out, act)) net_constructor = destruct(net) # W is in×out # b is out×1 @test net_constructor.num_params_network == in * out + out T = eltype(net_constructor.θ) netre = net_constructor(net_constructor.θ) x = randn(T, in, 10) y = net(x) yre = netre(x) @test all(y .== yre) # The next test is only violated with very small probability θrand = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θrand) yfalse = netfalse(x) @test all(y .!= yfalse) end end end end @testset "destruct RNN" for in = 1:3 for out = 1:3 @testset "Chain(RNN($in, $out))" begin net = Chain(RNN(in, out)) net_constructor = destruct(net) # Wx is in×out # Wh is out×out # b is out×1 # h0 is out×1 but we do not infer h0 so we drop it @test net_constructor.num_params_network == in * out + out * out + out T = eltype(net_constructor.θ) netre = net_constructor(net_constructor.θ) x = [randn(T, in, 1) for _ in 1:10] y = [net(xx) for xx in x][end] yre = [netre(xx) for xx in x][end] @test all(y .== yre) # Next one should only fail with very small probability (basically zero) θrand = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θrand) yfalse = [netfalse(xx) for xx in x][end] @test all(y .!= yfalse) end end end @testset "destruct LSTM" for in = 1:3 for out = 1:3 @testset "Chain(LSTM($in, $out))" begin net = Chain(LSTM(in, out)) net_constructor = destruct(net) # Wx is (out*4)×in because we need four Wx for input, forget, output and # cell input activation # Wh is (out*4)×(out) because we need four Wh for input, foget, output and # cell input activation # b is (out*4)×1 # We have two hidden states, c and h, both are out×1. We do not count # these since we do not infer them @test net_constructor.num_params_network == in * out * 4 + out * out * 4 + out * 4 T = eltype(net_constructor.θ) netre = net_constructor(net_constructor.θ) x = [randn(T, in, 1) for _ in 1:10] y = [net(xx) for xx in x][end] yre = [netre(xx) for xx in x][end] @test all(y .== yre) # The following should only fail with probability practically zero θfalse = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θfalse) yfalse = [netfalse(xx) for xx in x][end] @test all(y .!= yfalse) end end end @testset "destruct Dense-Dense" for in = 1:3 for out = 1:3 for act in [sigmoid, tanh, identity] @testset "Chain(Dense($in, $in), Dense($in, $out))" begin net = Chain(Dense(in, in, act), Dense(in, out)) net_constructor = destruct(net) @test net_constructor.num_params_network == (in * in + in) + (in * out + out) T = eltype(net_constructor.θ) x = randn(T, in, 10) netre = net_constructor(net_constructor.θ) y = net(x) yre = netre(x) @test all(y .== yre) θfalse = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θfalse) yfalse = netfalse(x) @test all(y .!= yfalse) end end end end @testset "destruct RNN-Dense" for in = 1:3 for out = 1:3 for act in [sigmoid, tanh, identity] @testset "Chain(RNN($in, $in), Dense($in, $out))" begin net = Chain(RNN(in, in), Dense(in, out, act)) net_constructor = destruct(net) @test net_constructor.num_params_network == (in * in + in * in + in) + (in * out + out) T = eltype(net_constructor.θ) x = [randn(T, in, 1) for _ in 1:10] netre = net_constructor(net_constructor.θ) y = [net(xx) for xx in x][end] yre = [netre(xx) for xx in x][end] @test all(y .== yre) θfalse = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θfalse) yfalse = [netfalse(xx) for xx in x][end] @test all(y .!= yfalse) end end end end @testset "destruct LSTM-Dense" for in = 1:3 for out = 1:3 for act in [sigmoid, tanh, identity] @testset "Chain(LSTM($in, $in), Dense($in, $out))" begin net = Chain(LSTM(in, in), Dense(in, out, act)) net_constructor = destruct(net) @test net_constructor.num_params_network == (in * in * 4 + in * in * 4 + in * 4) + (in * out + out) T = eltype(net_constructor.θ) x = [randn(T, in, 1) for _ in 1:10] netre = net_constructor(net_constructor.θ) y = [net(xx) for xx in x][end] yre = [netre(xx) for xx in x][end] @test all(y .== yre) θfalse = randn(T, net_constructor.num_params_network) netfalse = net_constructor(θfalse) yfalse = [netfalse(xx) for xx in x][end] @test all(y .!= yfalse) end end end end end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git
[ "MIT" ]
0.2.3
b248c6aefe448c9ad4efa106f31cd767d50c931d
code
1067
using BayesFlux import BayesFlux using Flux, Zygote @testset "Feedforward derivatives" begin net = Chain(Dense(1, 1)) nc = destruct(net) x = randn(Float32, 1, 100) y = randn(Float32, 100) like = FeedforwardNormal(nc, Gamma(2.0, 0.5)) prior = GaussianPrior(nc, 0.5f0) init = InitialiseAllSame(Normal(0f0, 0.5f0), like, prior) bnn = BNN(x, y, like, prior, init) θ = randn(Float32, bnn.num_total_params) ∇loglikeprior(bnn, θ, x, y) # If derivative above does not fail, the test has passed @test true end @testset "Recurrent derivatives" for rnn in [RNN, LSTM] net = Chain(rnn(1, 1)) nc = destruct(net) x = randn(Float32, 10, 1, 100) y = randn(Float32, 100) like = SeqToOneNormal(nc, Gamma(2.0, 0.5)) prior = GaussianPrior(nc, 0.5f0) init = InitialiseAllSame(Normal(0f0, 0.5f0), like, prior) bnn = BNN(x, y, like, prior, init) θ = randn(Float32, bnn.num_total_params) ∇loglikeprior(bnn, θ, x, y) # If derivative above does not fail, the test has passed @test true end
BayesFlux
https://github.com/enweg/BayesFlux.jl.git