-
Notifications
You must be signed in to change notification settings - Fork 9
Normalizer Wrapper #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
9a589fb
Normalizer
HenriDeh a47851a
typo
HenriDeh bd21824
typo
HenriDeh 2db7ec3
fix length
HenriDeh 9130fcd
fix
HenriDeh ed9c8ef
doc
HenriDeh dea0cca
Add a test for Float32
HenriDeh 85db627
Remove scalar normalization
HenriDeh f4ec153
adapt test
HenriDeh 9c74006
add rendering
HenriDeh 70d8623
use normalizedtrace instead of trajectory
HenriDeh c3aaf95
use a fetch api
HenriDeh 7eb77fe
move include order
HenriDeh bc73f34
tests
HenriDeh 1f04c11
compat
HenriDeh a84058a
fix tests and type presevation
HenriDeh 421fa78
fix a test
HenriDeh 9753cf1
remove the deepcopy
HenriDeh 564cb5b
increase test batchsize
HenriDeh 1a0b458
Merge branch 'main' into normalization
HenriDeh b142710
move to NormalizedTraces
HenriDeh 3d0416d
remove fetch and subtype
HenriDeh 7911566
add pretty printing
HenriDeh 18d2b97
Improve doc
HenriDeh ab2df32
improve some docs
HenriDeh 561a5f0
Fix multiplex
HenriDeh 9e26766
fix test typo
HenriDeh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
import OnlineStats: OnlineStats, Group, Moments, fit!, OnlineStat, Weight, EqualWeight, mean, std | ||
export scalar_normalizer, array_normalizer, NormalizedTrace, Normalizer | ||
import MacroTools.@forward | ||
|
||
""" | ||
Normalizer(::OnlineStat) | ||
|
||
Wraps an OnlineStat to be used by a [`NormalizedTrajectory`](@ref). | ||
""" | ||
struct Normalizer{OS<:OnlineStat} | ||
os::OS | ||
end | ||
|
||
@forward Normalizer.os OnlineStats.mean, OnlineStats.std, Base.iterate, normalize, Base.length | ||
|
||
|
||
|
||
#Treats last dim as batch dim | ||
function OnlineStats.fit!(n::Normalizer, data::AbstractArray) | ||
for d in eachslice(data, dims = ndims(data)) | ||
fit!(n.os, vec(d)) | ||
end | ||
n | ||
end | ||
|
||
function OnlineStats.fit!(n::Normalizer{<:Group}, y::AbstractVector) | ||
fit!(n.os, y) | ||
n | ||
end | ||
|
||
function OnlineStats.fit!(n::Normalizer, y) | ||
for yi in y | ||
fit!(n.os, vec(yi)) | ||
end | ||
n | ||
end | ||
|
||
function OnlineStats.fit!(n::Normalizer{<:Moments}, y::AbstractVector{<:Number}) | ||
for yi in y | ||
fit!(n.os, yi) | ||
end | ||
n | ||
end | ||
|
||
function OnlineStats.fit!(n::Normalizer, data::Number) | ||
fit!(n.os, data) | ||
n | ||
end | ||
|
||
""" | ||
scalar_normalizer(;weights = OnlineStats.EqualWeight()) | ||
|
||
Returns preconfigured normalizer for scalar traces such as rewards. By default, all samples have equal weights in the computation of the moments. | ||
See the [OnlineStats documentation](https://joshday.github.io/OnlineStats.jl/stable/weights/) to use variants such as exponential weights to favor the most recent observations. | ||
""" | ||
scalar_normalizer(; weight::Weight = EqualWeight()) = Normalizer(Moments(weight = weight)) | ||
|
||
""" | ||
array_normalizer(size::Tuple{Int}; weights = OnlineStats.EqualWeight()) | ||
|
||
Returns preconfigured normalizer for array traces such as vector or matrix states. | ||
`size` is a tuple containing the dimension sizes of a state. E.g. `(10,)` for a 10-elements vector, or `(252,252)` for a square image. | ||
By default, all samples have equal weights in the computation of the moments. | ||
See the [OnlineStats documentation](https://joshday.github.io/OnlineStats.jl/stable/weights/) to use variants such as exponential weights to favor the most recent observations. | ||
""" | ||
array_normalizer(size::NTuple{N,Int}; weight::Weight = EqualWeight()) where N = Normalizer(Group([Moments(weight = weight) for _ in 1:prod(size)])) | ||
|
||
|
||
""" | ||
NormalizedTrace(trace::Trace, normalizer::Normalizer) | ||
|
||
Wraps a [`Trace`](@ref) and a [`Normalizer`](@ref). When pushing new elements to the trace, a `NormalizedTrace` will first update a running estimate of the moments of that trace. | ||
When sampling a normalized trace, it will first normalize the samples using to zero mean and unit variance. | ||
|
||
preconfigured normalizers are provided for scalar (see [`scalar_normalizer`](@ref)) and arrays (see [`array_normalizer`](@ref)) | ||
|
||
#Example | ||
t = Trajectory( | ||
container=Traces( | ||
a_scalar_trace = NormalizedTrace(Float32[], scalar_normalizer()), | ||
a_non_normalized_trace=Bool[], | ||
a_vector_trace = NormalizedTrace(Vector{Float32}[], array_normalizer((10,))), | ||
a_matrix_trace = NormalizedTrace(Matrix{Float32}[], array_normalizer((252,252), weight = OnlineStats.ExponientialWeight(0.9f0))) | ||
), | ||
sampler=BatchSampler(3), | ||
controler=InsertSampleRatioControler(0.25, 4) | ||
) | ||
|
||
""" | ||
struct NormalizedTrace{T <: Trace, N <: Normalizer} | ||
trace::T | ||
normalizer::N | ||
end | ||
|
||
NormalizedTrace(x, normalizer) = NormalizedTrace(convert(Trace, x), normalizer) | ||
|
||
@forward NormalizedTrace.trace Base.length, Base.lastindex, Base.firstindex, Base.getindex, Base.view, Base.pop!, Base.popfirst!, Base.empty! | ||
|
||
Base.convert(::Type{Trace}, x::NormalizedTrace) = x #ignore conversion to Trace | ||
|
||
function Base.push!(nt::NormalizedTrace, x) | ||
fit!(nt.normalizer, x) | ||
push!(nt.trace, x) | ||
end | ||
|
||
function Base.append!(nt::NormalizedTrace, x) | ||
fit!(nt.normalizer, x) | ||
append!(nt.trace, x) | ||
end | ||
|
||
""" | ||
normalize!(os::Moments, x) | ||
|
||
Given an Moments estimate of the elements of x, a vector of scalar traces, | ||
normalizes x elementwise to zero mean, and unit variance. | ||
""" | ||
function normalize(os::Moments, x::AbstractVector) | ||
T = eltype(x) | ||
m, s = T(mean(os)), T(std(os)) | ||
return (x .- m) ./ s | ||
end | ||
|
||
""" | ||
normalize!(os::Group{<:AbstractVector{<:Moments}}, x) | ||
|
||
Given an os::Group{<:Tuple{Moments}}, that is, a multivariate estimator of the moments of each element of x, | ||
normalizes each element of x to zero mean, and unit variance. Treats the last dimension as a batch dimension if `ndims(x) >= 2`. | ||
""" | ||
function normalize(os::Group{<:AbstractVector{<:Moments}}, x::AbstractVector) | ||
T = eltype(x) | ||
m = [T(mean(stat)) for stat in os] | ||
s = [T(std(stat)) for stat in os] | ||
return (x .- m) ./ s | ||
end | ||
|
||
function normalize(os::Group{<:AbstractVector{<:Moments}}, x::AbstractArray) | ||
xn = similar(x) | ||
for (i, slice) in enumerate(eachslice(x, dims = ndims(x))) | ||
xn[repeat([:], ndims(x)-1)..., i] .= reshape(normalize(os, vec(slice)), size(x)[1:end-1]...) | ||
end | ||
return xn | ||
end | ||
|
||
function normalize(os::Group{<:AbstractVector{<:Moments}}, x::AbstractVector{<:AbstractArray}) | ||
xn = similar(x) | ||
for (i,el) in enumerate(x) | ||
xn[i] = normalize(os, vec(el)) | ||
end | ||
return xn | ||
end | ||
|
||
function fetch(nt::NormalizedTrace, inds) | ||
batch = deepcopy(fetch(nt.trace, inds)) | ||
normalize(nt.normalizer.os, batch) | ||
end | ||
|
||
function sample(s, nt::NormalizedTrace) | ||
batch = deepcopy(sample(s, nt.trace)) | ||
normalize(nt.normalizer.os, batch) | ||
HenriDeh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
using Test | ||
using Trajectories | ||
import Trajectories.normalize | ||
import OnlineStats: fit!, mean, std | ||
|
||
@testset "normalization.jl" begin | ||
#scalar normalization | ||
rewards = [1.:10;] | ||
rn = scalar_normalizer() | ||
fit!(rn, rewards) | ||
batch_reward = normalize(rn, [6.,5.,10.]) | ||
@test batch_reward ≈ ([6.,5.,10.] .- mean(1:10))./std(1:10) | ||
#vector normalization | ||
states = reshape([1:50;], 5, 10) | ||
sn = array_normalizer((5,)) | ||
fit!(sn, states) | ||
@test [mean(stat) for stat in sn] == [mean((1:5:46) .+i) for i in 0:4] | ||
batch_states =normalize(sn, reshape(repeat(5.:-1:1, 5), 5,5)) | ||
@test all(length(unique(x)) == 1 for x in eachrow(batch_states)) | ||
#array normalization | ||
states = reshape(1.:250, 5,5,10) | ||
sn = array_normalizer((5,5)) | ||
fit!(sn, eachslice(states, dims = 3)) | ||
batch_states = normalize(sn, collect(states)) | ||
|
||
#NormalizedTrace | ||
t = Trajectory( | ||
container=Traces( | ||
a= NormalizedTrace(Float32[], scalar_normalizer()), | ||
b=Int[], | ||
c=NormalizedTrace(Vector{Float32}[], array_normalizer((10,))) #TODO check with ElasticArrays and Episodes | ||
), | ||
sampler=BatchSampler(30000), | ||
controler=InsertSampleRatioControler(Inf, 0) | ||
) | ||
append!(t, a = [1,2,3], b = [1,2,3], c = eachcol(reshape(1f0:30, 10,3))) | ||
push!(t, a = 2, b = 2, c = fill(mean(1:30), 10)) | ||
@test mean(t.container[:a].trace.x) ≈ 2. | ||
@test std(t.container[:a].trace.x) ≈ std([1,2,2,3]) | ||
a,b,c = take!(t) | ||
@test eltype(a) == Float32 | ||
@test mean(a) ≈ 0 atol = 0.01 | ||
@test mean(b) ≈ 2 atol = 0.01 #b is not normalized | ||
@test eltype(first(c)) == Float32 | ||
@test all(isapprox(0f0, atol = 0.01), vec(mean(reduce(hcat,c), dims = 2))) | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.