【问题标题】:creating a struct in Julia based on variable input基于变量输入在 Julia 中创建结构
【发布时间】:2020-05-05 20:03:12
【问题描述】:

我是 Julia 的新手,正在尝试通过神经网络项目学习一些东西。 我想根据我作为输入提供的层数为网络创建一个结构。这是基于此处的示例:(http://neuralnetworksanddeeplearning.com/chap1.html#implementing_our_network_to_classify_digits)。 (非常好)

我正在从该文本中复制代码:

class Network(object):
    def __init__(self, sizes):
        self.num_layers = len(sizes)
        self.sizes = sizes
        self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
        self.weights = [np.random.randn(y, x) 
                        for x, y in zip(sizes[:-1], sizes[1:])]

在此代码中,列表大小包含各个层中的神经元数量。因此,例如,如果我们想创建一个 Network 对象,其中第一层有 2 个神经元,第二层有 3 个神经元,最后一层有 1 个神经元,我们可以使用以下代码:

net = Network([2, 3, 1])"

我在 Julia 中尝试过类似的方法:

struct NTWRK(nt)
    numlayers=length(nt)
    Nsizes=nt
    biases= [rand(Float32,nt[i+1]) for i=1:length(nt)-1]
    weights=[rand(Float32,(nt[i+1],nt[i])) for i=1:length(nt)-1]
end

network=NTWRK([784, 16, 16, 10])

我收到以下错误:

ERROR: syntax: "numlayers = length(nt)" inside type definition is reserved
Stacktrace:
   [1] top-level scope at none:0

我尝试了各种方法,但根据我在开始时提供的输入,我无法获得包含所有预期字段的对象。有什么建议吗?

谢谢!

【问题讨论】:

    标签: struct julia


    【解决方案1】:

    所以struct NTWRK 是一个类型定义,但您将它视为一个函数。 struct NTWRK(nt) 语法无效。

    将其与您的 Python 代码进行比较,您应该意识到 __init__() 是一个构造函数,因此要在 Julia 中做同样的事情,您还需要一个构造函数。

    所以首先你需要声明类型,然后,你可以定义构造函数。

    # First, the declaration of the struct
    struct NTWRK
        Nsizes::Vector{Int}
        biases::Vector{Vector{Float32}} 
        weights::Vector{Matrix{Float32}}
    end
    
    # There has already been automatically created a constructor, but we want
    # to create one that accepts just a single input argument:
    function NTWRK(nt::Vector)
        biases = [rand(Float32,nt[i+1]) for i in 1:length(nt)-1]
        weights = [rand(Float32,(nt[i+1],nt[i])) for i in 1:length(nt)-1]
        return NTWRK(nt, biases, weights) # here we call the pre-existing constructor
    end
    numlayers(nw::NTWRK) = length(nw.Nsizes)
    

    我将numlayers 移到结构本身之外,因为当从Nsizes 字段中读取它时,将其存储为单独的字段似乎毫无意义。

    【讨论】:

    • 嗨,这似乎有效!谢谢你,我很感激。我不确定我是否完全理解正在发生的事情,但我明天会再研究一下。
    【解决方案2】:

    你可以像这样使用外部构造函数:

    julia> struct NTWRK
               numlayers
               NSizes
           end
    
    # This is the outer constructor that accepts the nt input
    julia> NTWRK(nt) = NTWRK(length(nt), nt)
    NTWRK
    
    julia> NTWRK([1,2,3])
    NTWRK(3, [1, 2, 3])
    

    【讨论】:

    • 永远不要使用无类型的struct 字段。
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多