Struct 基于变量输入在Julia中创建结构
我是朱莉娅的新手,正在尝试通过一个神经网络项目学习一些东西。 我想创建一个网络结构的基础上有多少层我作为输入。这是基于这里的一个例子:()。(非常好) 我正在从该文本复制代码:Struct 基于变量输入在Julia中创建结构,struct,julia,Struct,Julia,我是朱莉娅的新手,正在尝试通过一个神经网络项目学习一些东西。 我想创建一个网络结构的基础上有多少层我作为输入。这是基于这里的一个例子:()。(非常好) 我正在从该文本复制代码: 类网络(对象): def u u初始(自身,尺寸): self.num_layers=len(大小) self.size=大小 self.biases=[np.random.randn(y,1)表示y的大小[1:] 自权重=[np.random.randn(y,x) 对于拉链中的x、y(尺寸[:-1],尺寸[1:])]
类网络(对象):
def u u初始(自身,尺寸):
self.num_layers=len(大小)
self.size=大小
self.biases=[np.random.randn(y,1)表示y的大小[1:]
自权重=[np.random.randn(y,x)
对于拉链中的x、y(尺寸[:-1],尺寸[1:])]
在此代码中,列表大小包含各个层中的神经元数量。例如,如果我们想创建一个网络对象,第一层有2个神经元,第二层有3个神经元,最后一层有1个神经元,我们可以用下面的代码:
net = Network([2, 3, 1])"
我在朱莉娅身上也尝试过类似的东西:
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
我尝试了各种各样的方法,但根据我在开始时给出的输入,我无法获得包含所有预期字段的对象。有什么建议吗
谢谢 您可以使用这样的外部构造函数:
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 NTWRK
是一个类型定义,但您将其视为一个函数<代码>结构NTWRK(nt)是无效语法
将其与Python代码进行比较,您应该意识到\uuuu init\uuuu()
是一个构造函数,因此在Julia中执行同样的操作也需要一个构造函数
因此,首先需要声明类型,然后可以定义构造函数
我将
numlayers
移到结构本身之外,因为当它从Nsizes
字段中读取时,将其存储为单独的字段似乎没有意义。嗨,这似乎可行!谢谢,我很感激。我不确定我是否完全理解正在发生的事情,但我明天会进一步研究。永远不要使用非类型的struct
字段。
# 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)