Julia 朱莉娅的打字错误

Julia 朱莉娅的打字错误,julia,Julia,我创建了一个名为HousingData的新结构,并定义了诸如iterate和length之类的函数。但是,当我为我的HousingData对象使用collect函数时,我遇到了以下错误 TypeError:在typeassert中,应为整数,但得到了Float64类型的值 import Base: length, size, iterate struct HousingData x y batchsize::Int shuffle::Bool num_in

我创建了一个名为HousingData的新结构,并定义了诸如iterate和length之类的函数。但是,当我为我的HousingData对象使用collect函数时,我遇到了以下错误

TypeError:在typeassert中,应为整数,但得到了Float64类型的值

import Base: length, size, iterate
struct HousingData
    x
    y
    batchsize::Int
    shuffle::Bool
    num_instances::Int

    function HousingData(
        x, y; batchsize::Int=100, shuffle::Bool=false, dtype::Type=Array{Float64})
    
        new(convert(dtype,x),convert(dtype,y),batchsize,shuffle,size(y)[end])
    end
end

function length(d::HousingData)
    
    return ceil(d.num_instances/d.batchsize)
end



function iterate(d::HousingData, state=ifelse(
    d.shuffle, randperm(d.num_instances), collect(1:d.num_instances)))
   
     
    if(length(state)==0)
        return nothing
    end
    return ((d.x[:,state[1]],d.y[:,state[1]]),state[2:end])
end


x1 = randn(5, 100); y1 = rand(1, 100);
obj = HousingData(x1,y1; batchsize=20)


collect(obj)

您的代码中存在多个问题。第一个与
length
相关,它不返回整数,而是一个浮点。这可以通过
ceil
的行为来解释:

julia> ceil(3.8)
4.0 # Notice: 4.0 (Float64) and not 4 (Int)
您可以轻松解决此问题:

function length(d::HousingData)
    return Int(ceil(d.num_instances/d.batchsize))
end
另一个问题在于迭代函数的逻辑,它与公布的长度不一致。举一个比你小的例子:

julia>x1=[i+j/10代表1:2中的i,j代表1:6]
2×6数组{Float64,2}:
1.1  1.2  1.3  1.4  1.5  1.6
2.1  2.2  2.3  2.4  2.5  2.6
#顺便说一句,除非你真的想使用1xN矩阵
#在Julia中,在这种情况下使用1D向量更为惯用
julia>y1=[Float64(j)代表1:1中的i,j代表1:6]
1×6数组{Float64,2}:
1.0  2.0  3.0  4.0  5.0  6.0
julia>obj=HousingData(x1,y1;batchsize=3)
住房数据([1.1 1.2…1.5 1.6;2.1 2.2…2.5 2.6],[1.0 2.0…5.0 6.0],3,假,6)
朱莉娅>长度(obj)
2.
julia>枚举(obj)中的(i,e)
println(“$i->$e”)
结束
1 -> ([1.1, 2.1], [1.0])
2 -> ([1.2, 2.2], [2.0])
3 -> ([1.3, 2.3], [3.0])
4 -> ([1.4, 2.4], [4.0])
5 -> ([1.5, 2.5], [5.0])
6 -> ([1.6, 2.6], [6.0])
迭代器生成6个元素,而这个对象的
长度
只有2个。这解释了
收集
错误的原因:

julia> collect(obj)
ERROR: ArgumentError: destination has fewer elements than required
了解您的代码,您可能是修复其逻辑的最佳人选