我是 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:])]
在此代码中,列表大小包含各个层中神经元的数量。因此,例如,如果我们想创建一个第一层有 2 个神经元、第二层有 3 个神经元、最后一层有 1 个神经元的 Network 对象,我们可以使用以下代码来实现:
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 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
字段中轻松读取它时,将其存储为单独的字段似乎毫无意义。
关于struct - 根据变量输入在 Julia 中创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61622028/