Training a fully-connected multilayer neural network on corrected data
In this example, data processing and training of a neural network model on corrected data will be discussed. A sliding window method will be demonstrated to divide the training and test samples into training datasets, and model parameters will be determined to obtain the most accurate predictions.
Launching the necessary libraries:
Pkg.add(["Statistics", "CSV", "Flux", "Optimisers"])
using Statistics
using CSV
using DataFrames
using Flux
using Plots
using Flux: train!
using Optimisers
Preparation of training and test sample:
Loading data for training the model:
df = DataFrame(CSV.File("$(@__DIR__)/data.csv"));
The data was saved after running the example /start/examples/data_analysis/data_processing.ipynb.
Formation of the training dataset:
The entire dataset was divided into training sample and test sample. The training sample was 0.8 of the whole dataset and the test sample was 0.2.
T = df[1:1460,3]; # определение обучающего набора данных, весь датасет 1825 строк
first(df, 5)
Division of vector T into batches of 100 observations:
batch_starts = 1:1:1360 # определение диапазона для цикла
weather_batches = [] # определение пустого массива для записи результатов выполнения цикла
for start in batch_starts
dop = T[start:start+99] # батч на текущем временном шаге
weather_batches = vcat(weather_batches, dop) # запись батча в массив
end
A batch is a small data set that can serve as a training set for building a prediction model. It is taken from the initial training set T using the sliding window method.
Sliding window method:
where x is the observation and y1 is the predicted value.
Conversion of the obtained set into a vector-string:
weather_batches = weather_batches'
Changing the shape of the array to match the length of the batched set above:
weather_batches = reshape(weather_batches, (100,:))
X = weather_batches # переприсвоение
Defining an array of target values:
Y = (T[101:1460]) # отсчёт начинается с 101, так как предыдущие 100 наблюдений используются в качестве исходных данных
Y = Y'
Conversion into a format acceptable for processing by a neural network:
X = convert(Array{Float32}, X)
Y = convert(Array{Float32}, Y)
Formation of a test data set:
Splitting the test sample into batches of 100 observations in length:
X_test = df[1461:1820, 3] # определение тестового набора данных
batch_starts_test = 1:1:261 # определение диапазона для цикла
test_batches = [] # определение пустого массива для записи результатов выполнения цикла
for start in batch_starts_test
dop = X_test[start:start+99] # батч на текущем временном шаге
test_batches = vcat(test_batches, dop) # запись батча в массив
end
test_batches = reshape(test_batches, (100,:)) # изменение формы массива для соответствия длине батча, указанной выше:
X_test = convert(Array{Float32}, test_batches) # преобразование в формат приемлимый для обработки нейросетью
Building and training a neural network:
Defining the architecture of a neural network:
model = Flux.Chain(
Dense(100 => 50, elu),
Dense(50 => 25, elu),
Dense(25 => 5, elu),
Dense(5 => 1)
)
Determination of training parameters:
# Инициализация оптимизатора
learning_rate = 0.001f0
opt = Optimisers.Adam(learning_rate)
state = Optimisers.setup(opt, model) # Создание начального состояния
# Функция потерь
loss(model, x, y) = Flux.mse(model(x), y)
Training the model:
loss_history = []
epochs = 200
for epoch in 1:epochs
# Вычисление градиентов
grads = gradient(model) do m
loss(m, X, Y)
end
# Обновление модели и состояния
state, model = Optimisers.update(state, model, grads[1])
# Расчет и сохранение потерь
current_loss = loss(model, X, Y)
push!(loss_history, current_loss)
# Вывод потерь на каждом шаге
if epoch == 1 || epoch % 10 == 0
println("Epoch $epoch: Loss = $current_loss")
end
end
Visualising the change in the loss function:
plot((1:epochs), loss_history, title="Изменение функции потерь", xlabel="Эпоха", ylabel="Функция потерь")
Obtaining forecast values:
y_hat_raw = model(X_test) # загрузка тестовой выборки в модель, получение прогноза
y_pred = y_hat_raw'
y_pred = y_pred[:,1]
y_pred = convert(Vector{Float64}, y_pred)
first(y_pred, 5)
Visualisation of predicted values:
days = df[:,1] # формирование массива дней, начиная с первого наблюдения
first(days, 5)
Connecting backend - graph display method:
plotlyjs()
Generating a dataset from the initial dataset for comparison:
df_T = df[:, 3]#df[1471:1820, 3]
first(df_T, 5)
Plotting temperature vs. time using initial and predicted data:
plot(days, df_T)#plot(days, T[11:end]) #T[11:end]
plot!(days[1560:1820], y_pred)
Since the original dataset has areas where missing values have been replaced by linear interpolation, it is difficult to evaluate the performance of the trained neural network model on a straight line.
For this purpose, real data without missing values were loaded:
real_data = DataFrame(CSV.File("$(@__DIR__)/real_data.csv"));
Plotting temperature vs. time using real and predicted data:
plot(real_data[1:261,2])
plot!(y_pred)
Let's check the relationship between the obtained values using Pearson correlation, thus assessing the accuracy of the obtained model:
corr_T = cor(y_pred,real_data[1:261,2])
Pearson's correlation coefficient can take values from -1 to 1, where 0 will mean no relationship between the variables, and -1 and 1 - close relationship (inverse and direct dependence respectively).
Conclusions:
This case study preprocessed temperature observation data for the last five years and defined the neural network architecture, optimiser parameters and loss function.
The model was trained and showed a fairly high, but not perfect convergence of predicted values to real data. To improve the quality of prediction, the neural network can be modified by changing the architecture of layers and increasing the training sample.