When i run this code appears this error:ERROR: UndefVarError: GPU
not defined
Stacktrace:
[1] top-level scope
CODE:
using CUDA
using Flux
using Flux.Data: DataLoader
using Flux: onehotbatch, onecold, crossentropy, throttle
using Statistics
using Base.Iterators: partition
using MLDatasets: CIFAR10
devices = GPU.devices()
if length(devices) > 0
device = devices[1]
CUDA.allowscalar(false)
else
device = CUDA.CPU
end
CUDA.device!(device)
train_x, train_y = CIFAR10.traindata(Float32)
test_x, test_y = CIFAR10.testdata(Float32)
train_y = onehotbatch(train_y, 0:9)
test_y = onehotbatch(test_y, 0:9)
batch_size = 64
train_data = DataLoader((train_x, train_y), batchsize=batch_size, shuffle=true)
test_data = DataLoader((test_x, test_y), batchsize=batch_size)
model = Chain(
Conv((3, 3), 3=>16, relu),
MaxPool((2, 2)),
Conv((3, 3), 16=>32, relu),
MaxPool((2, 2)),
x → reshape(x, :, size(x, 4)),
Dense(3266, 256, relu),
Dense(256, 10),
softmax
) |> gpu
loss(x, y) = crossentropy(model(x), y)
optimizer = ADAM(0.001)
n_epochs = 10
for epoch in 1:n_epochs
println(“Epoch: $epoch”)
Flux.train!(loss, params(model), train_data, optimizer)
end
function test_accuracy(data_loader)
acc = 0.0
for (x, y) in data_loader
acc += sum(onecold(model(x)) .== onecold(y))
end
return acc / length(data_loader)
end
accuracy = test_accuracy(test_data)
println(“Test Accuracy: $accuracy”)