我有以下代码试图在 Julia 中训练神经网络,但每当我尝试使用 Flux.train 时我都会收到错误消息!
using Flux, CSV, DataFrames, Random, Statistics, Plots
# Load the data
data = CSV.read("daily_stock_returns.csv")
# Split the data into training and testing sets
train_data = data[1:800, :]
test_data = data[801:end, :]
# Define the input and output variables
inputs = Matrix(train_data[:, 2:end])
outputs = Matrix(train_data[:, 1])
# Define the neural network architecture
n_inputs = size(inputs, 2)
n_hidden = 10
n_outputs = 1
model = Chain(
Dense(n_inputs, n_hidden, relu),
Dense(n_hidden, n_outputs)
)
# Define the loss function
loss(x, y) = Flux.mse(model(x), y)
# Define the optimizer
optimizer = ADAM()
# Train the model
n_epochs = 100
for epoch in 1:n_epochs
Flux.train!(loss, params(model), [(inputs, outputs)], optimizer)
end
# Test the model
test_inputs = Matrix(test_data[:, 2:end])
test_outputs = Matrix(test_data[:, 1])
predictions = Flux.predict(model, test_inputs)
test_loss = Flux.mse(predictions, test_outputs)
# Print the test loss
println("Test loss: $test_loss")
当我运行这段代码时:
# Train the model
n_epochs = 100
for epoch in 1:n_epochs
Flux.train!(loss, params(model), [(inputs, outputs)], optimizer)
end
我收到以下错误。
UndefVarError: params not defined
Stacktrace:
[1] top-level scope
@ .\In[16]:4
[2] eval
@ .\boot.jl:368 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1428
我试过卸载和安装都没有改善。我该如何解决这个错误?
这是因为
Fux.params
(见文档)默认不导出。您可以将 params
替换为 Flux.params
(据我所知,这是文档中经常这样做的方式),或者将 using Flux
替换为 using Flux: params
(第二个选项可能不太理想,因为它添加了一个名称这对你的命名空间来说真的很通用)。