Julia中使用Flux.train!训练神经网络出现params未定义错误的解决方法
问题:Flux.train! 运行报错 UndefVarError: params not defined
问题描述
我编写了以下用于在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
我已尝试卸载并重新安装相关包,但问题未解决。请问该如何修复?
解决方案
这个错误源于Flux 0.13+版本已移除params()函数,改用了更简洁的训练API。以下是两种修复方式:
方式1:使用新版Flux训练API(推荐)
新版Flux.train!无需手动传入参数集合,直接传入模型、数据迭代器和优化器即可。同时推荐用DataLoader做批次处理,提升训练效率:
# 替换原训练循环代码 data_loader = Flux.DataLoader((inputs, outputs), batchsize=32, shuffle=true) for epoch in 1:n_epochs Flux.train!(loss, model, data_loader, optimizer) end
方式2:兼容旧版API(不推荐,会触发废弃警告)
如果需要保留旧写法,需显式导入Flux.params:
# 在开头的using语句后添加 using Flux: params # 原训练代码可保留,但会收到废弃提示 for epoch in 1:n_epochs Flux.train!(loss, params(model), [(inputs, outputs)], optimizer) end
额外修复:预测函数问题
你的代码中Flux.predict(model, test_inputs)也会报错,新版Flux中直接调用模型即可完成预测:
# 替换预测代码 predictions = model(test_inputs)
完整修正后的代码示例
using Flux, CSV, DataFrames, Random, Statistics, Plots # Load the data(新版CSV.read需指定DataFrame类型) data = CSV.read("daily_stock_returns.csv", DataFrame) # 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 with DataLoader n_epochs = 100 data_loader = Flux.DataLoader((inputs, outputs), batchsize=32, shuffle=true) for epoch in 1:n_epochs Flux.train!(loss, model, data_loader, optimizer) # 可选:打印每轮训练损失 train_loss = loss(inputs, outputs) println("Epoch $epoch, Train Loss: $train_loss") end # Test the model test_inputs = Matrix(test_data[:, 2:end]) test_outputs = Matrix(test_data[:, 1]) predictions = model(test_inputs) test_loss = Flux.mse(predictions, test_outputs) # Print the test loss println("Test loss: $test_loss")
内容的提问来源于stack exchange,提问作者Dammon
相关产品推荐
相关产品推荐

