I write some code below and it works correctly.
function value_counter(data, feature_name)
feature_col = unique(data, feature_name)
unique_val = unique!(unique(data, feature_name))
count_val = []
value_counts_dict = Dict()
for val in unique_val
counter = 0
for col_val in feature_col
if val == col_val
counter += 1
end
end
append!(count_val, counter)
value_counts_dict[val] = counter
end
return value_counts_dict
end
But when I run it over three times. It appears a bug 'Stackoverflow' and I think the error from the unique method. How can I free the stack after running the code?
Update: I try to redefine unique method. It is still errors but this time it's in 'in' method
ERROR: LoadError: StackOverflowError:
Stacktrace:
[1] in(x::SubString{String}, itr::Vector{Any})
# Base .\operators.jl:1283
[2] redefine_unique(data::Vector{Any})
# Main E:\Study\3_grade\Csttnt\Project03_decision_tree\Decision_Tree.jl:35
It's probably not the in method or unique method itself that's causing the stack overflow. Rather, you have some large, probably recursive, stack that just happens to hit the stack size limit when it gets to that downstream function. What you should look for in the stack is where the recursive part is. What functions are being called repeatedly? You may be missing a base case somewhere, or perhaps introduced unexpected recursion into an overwritten Base function, as Sundar mentioned.
Related
I'm very new to Julia, and I'm trying to just pass an array of numbers into a function and count the number of zeros in it. I keep getting the error:
ERROR: UndefVarError: array not defined
I really don't understand what I am doing wrong, so I'm sorry if this seems like such an easy task that I can't do.
function number_of_zeros(lst::array[])
count = 0
for e in lst
if e == 0
count + 1
end
end
println(count)
end
lst = [0,1,2,3,0,4]
number_of_zeros(lst)
There are two issues with your function definition:
As noted in Shayan's answer and Dan's comment, the array type in Julia is called Array (capitalized) rather than array. To see:
julia> array
ERROR: UndefVarError: array not defined
julia> Array
Array
Empty square brackets are used to instantiate an array, and if preceded by a type, they specifically instantiate an array holding objects of that type:
julia> x = Int[]
Int64[]
julia> push!(x, 3); x
1-element Vector{Int64}:
3
julia> push!(x, "test"); x
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64
Thus when you do Array[] you are actually instantiating an empty vector of Arrays:
julia> y = Array[]
Array[]
julia> push!(y, rand(2)); y
1-element Vector{Array}:
[0.10298669573927233, 0.04327245960128345]
Now it is important to note that there's a difference between a type and an object of a type, and if you want to restrict the types of input arguments to your functions, you want to do this by specifying the type that the function should accept, not an instance of this type. To see this, consider what would happen if you had fixed your array typo and passed an Array[] instead:
julia> f(x::Array[])
ERROR: TypeError: in typeassert, expected Type, got a value of type Vector{Array}
Here Julia complains that you have provided a value of the type Vector{Array} in the type annotation, when I should have provided a type.
More generally though, you should think about why you are adding any type restrictions to your functions. If you define a function without any input types, Julia will still compile a method instance specialised for the type of input provided when first call the function, and therefore generate (most of the time) machine code that is optimal with respect to the specific types passed.
That is, there is no difference between
number_of_zeros(lst::Vector{Int64})
and
number_of_zeros(lst)
in terms of runtime performance when the second definition is called with an argument of type Vector{Int64}. Some people still like type annotations as a form of error check, but you also need to consider that adding type annotations makes your methods less generic and will often restrict you from using them in combination with code other people have written. The most common example of this are Julia's excellent autodiff capabilities - they rely on running your code with dual numbers, which are a specific numerical type enabling automatic differentiation. If you strictly type your functions as suggested (Vector{Int}) you preclude your functions from being automatically differentiated in this way.
Finally just a note of caution about the Array type - Julia's array's can be multidimensional, which means that Array{Int} is not a concrete type:
julia> isconcretetype(Array{Int})
false
to make it concrete, the dimensionality of the array has to be provided:
julia> isconcretetype(Array{Int, 1})
true
First, it might be better to avoid variable names similar to function names. count is a built-in function of Julia. So if you want to use the count function in the number_of_zeros function, you will undoubtedly face a problem.
Second, consider returning the value instead of printing it (Although you didn't write the print function in the correct place).
Third, You can update the value by += not just a +!
Last but not least, Types in Julia are constantly introduced with the first capital letter! So we don't have an array standard type. It's an Array.
Here is the correction of your code.
function number_of_zeros(lst::Array{Int64})
counter = 0
for e in lst
if e == 0
counter += 1
end
end
return counter
end
lst = [0,1,2,3,0,4]
number_of_zeros(lst)
would result in 2.
Additional explanation
First, it might be better to avoid variable names similar to function names. count is a built-in function of Julia. So if you want to use the count function in the number_of_zeros function, you will undoubtedly face a problem.
Check this example:
function number_of_zeros(lst::Array{Int64})
count = 0
for e in lst
if e == 0
count += 1
end
end
return count, count(==(1), lst)
end
number_of_zeros(lst)
This code will lead to this error:
ERROR: MethodError: objects of type Int64 are not callable
Maybe you forgot to use an operator such as *, ^, %, / etc. ?
Stacktrace:
[1] number_of_zeros(lst::Vector{Int64})
# Main \t.jl:10
[2] top-level scope
# \t.jl:16
Because I overwrote the count variable on the count function! It's possible to avoid such problems by calling the function from its module:
function number_of_zeros(lst::Array{Int64})
count = 0
for e in lst
if e == 0
count += 1
end
end
return count, Base.count(==(1), lst)
The point is I used Base.count, then the compiler knows which count I mean by Base.count.
I have this error
ERROR: MethodError: vcat(::Array{Real,2}, ::TrackedArray{…,Array{Float32,2}}) is ambiguous. Candidates:
vcat(364::AbstractArray, x::Union{TrackedArray, TrackedReal}, xs::Union{Number, AbstractArray}...) in Tracker at C:\Users\Henri\.julia\packages\Tracker\6wcYJ\src\lib\array.jl:167
vcat(A::Union{AbstractArray{T,2}, AbstractArray{T,1}} where T...) in Base at abstractarray.jl:1296
Possible fix, define
vcat(::Union{AbstractArray{T,2}, AbstractArray{T,1}} where T, ::Union{TrackedArray{T,1,A} where A<:AbstractArray{T,1} where T, TrackedArray{T,2,A} where A<:AbstractArray{T,2} where T}, ::Vararg{Union{AbstractArray{T,2}, AbstractArray{T,1}} where T,N} where N)
Telling me that two vcat() functions are ambiguous. I want to use the Base.vcat() function but using it explicitly throws the same error. Why is that ? And what is this "possible fix" proposed by the error throw?
Moreover, when I call manually each line in the REPL no error is thrown. I do not understand this behavior. This only happens when vcat() is in a function called inside another function. Like in my example below.
Here is a code that reproduces the error:
using Flux
function loss(a, b, net, net2)
net2(vcat(net(a),a))
end
function test()
opt = ADAM()
net = Chain(Dense(3,3))
net2 = Chain(Dense(6,1))
L(a, b) = loss(a, b, net, net2)
data = tuple(rand(3,1), rand(3,1))
xs = Flux.params(net)
gs = Tracker.gradient(() -> L(data...), xs)
Tracker.update!(opt, xs, gs)
end
As mentionned in comments with Henri.D, we've managed to fix it by being carreful with the type of a which was an Array of Float64, default type returned by rand whereas net(a) returned a TrackedArray of Float32 and made impossible to vcat it with a.
I've managed to fix vcat by changing your loss function with this: net2(vcat(net(a),Float32.(a))) because vcat couldn't concatenate as net(a) was a Float32 Array and a a Float64 one. Then L(data...) is a TrackedArray of 1 element whereas I think you need a Float32 that's why I finally replace loss function by net2(vcat(net(a),Float32.(a)))[1]
Someone please help me understand this. I have the following code below. I am trying to append index[i]-1 to an empty array. However I am getting this error: "BoundsError: attempt to access 0-element Array{Any,1} at index [1]" :
sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
n_minus_1[i].append(sample_size_array[i] -1)
end
println(n_minus_1)
If Julia does not understand array[0] then why is i starting at 0 and not at 1?
Your code has two problems:
in the first iteration you are trying to access n_minus_1 array at index 1 while this array is still empty (has 0 length) - this throws you an error;
in Julia you do not invoke methods using a . (this symbol is used for different purposes - in this case it is parsed as field access and also would throw an error later)
To solve both those problems use push! function which appends an element at the end of an array. The code could look like this:
sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
push!(n_minus_1, sample_size_array[i]-1)
end
println(n_minus_1)
However in this case the whole operation can be written even simpler as:
n_minus_1 = sample_size_array .- 1
and you do not need any loop (and here you see another use of . in Julia - in this case we use it to signal that we want to subtract 1 from every element of sample_size_array).
Just messing with elixir result got an error that I cannot figure out.Here is my snippet,I implemented a simple Parallel map function for some api calls. func is the function where the actual calls are made and it returns {:ok,result} or {:error,reason} which I handle after the mapping in a different function
Originally
def pmap(collection,func,limit \\ 5000) do
collection
|> Enum.map(&Task.async(func.(&1)))
|> Enum.map(&Task.await(&1,limit))
Got the error so changed it to this for readability
def pmap(collection,func,limit) do
collection
|>Enum.map(fn(x) -> Task.async(func.(x)) end)
|>Enum.map(fn(task) -> Task.await(task,limit) end)
The error I am getting states
[error] Task #PID<0.197.0> started from #PID<0.187.0> terminating
** (BadFunctionError) expected a function, got: {:ok,result}
erlang.apply/2
(elixir) lib/task/supervised.ex:85: Task.Supervised.do_apply/2
(elixir) lib/task/supervised.ex:36: Task.Supervised.reply/5
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Function: &:erlang.apply/2
From what I gather it is assuming that the actual task collection element is being passed as the function
So I modified the function to
IO.puts "PMAP BEGUN"
tasks = collection
|> Enum.map(fn(x) -> Task.async(func.(x)) end)
answer = Enum.map(tasks,fn(task) -> Task.await(task,limit) end)
IO.puts "PMAP DONE"
answer
The IO.puts were for debugging.So I guess the error happens on the second map as PMAP DONE is never displayed. I still have the same error.
What exactly is wrong here? I have written the same function before almost verbatim and it worked.
The problem you're experiencing happens on line:
|> Enum.map(fn(x) -> Task.async(func.(x)) end)
to make it work you need to wrap function execution with anonymous function, like:
|> Enum.map(fn(x) -> Task.async(fn -> func.(x) end) end)
This due to fact if you run func.(x) this will evaluate, and the result of evaluation will be passed to Task.async/1, while when you wrap it with function, it will be up to Task to execute it.
The hint is indicated in error message:
** (BadFunctionError) expected a function, got: {:ok,result}
Hope this helps!
This snippet of F# code
let rec reformat = new EventHandler(fun _ _ ->
b.TextChanged.RemoveHandler reformat
b |> ScrollParser.rewrite_contents_of_rtb
b.TextChanged.AddHandler reformat
)
b.TextChanged.AddHandler reformat
results in the following warning:
traynote.fs(62,41): warning FS0040: This and other recursive references to the object(s) being defined will be checked for initialization-soundness at runtime through the use of a delayed reference. This is because you are defining one or more recursive objects, rather than recursive functions. This warning may be suppressed by using '#nowarn "40"' or '--nowarn:40'.
Is there a way in which the code can be rewritten to avoid this warning? Or is there no kosher way of having recursive objects in F#?
Your code is a perfectly fine way to construct a recursive object. The compiler emits a warning, because it cannot guarantee that the reference won't be accessed before it is initialized (which would cause a runtime error). However, if you know that EventHandler does not call the provided lambda function during the construction (it does not), then you can safely ignore the warning.
To give an example where the warning actually shows a problem, you can try the following code:
type Evil(f) =
let n = f()
member x.N = n + 1
let rec e = Evil(fun () ->
printfn "%d" (e:Evil).N; 1)
The Evil class takes a function in a constructor and calls it during the construction. As a result, the recursive reference in the lambda function tries to access e before it is set to a value (and you'll get a runtime error). However, especially when working with event handlers, this is not an issue (and you get the warnning when you're using recursive objects correctly).
If you want to get rid of the warning, you can rewrite the code using explicit ref values and using null, but then you'll be in the same danger of a runtime error, just without the warning and with uglier code:
let foo (evt:IEvent<_, _>) =
let eh = ref null
eh := new EventHandler(fun _ _ ->
evt.RemoveHandler(!eh) )
evt.AddHandler(!eh)