99 lines
No EOL
4.1 KiB
Python
99 lines
No EOL
4.1 KiB
Python
# -------------------------------------------------------#
|
|
# Шаблон для созданиия и тестирования различных моделей #
|
|
# нейронных сетей на одном наборе данных. #
|
|
# При обучении моделей из обучающей выборки выделяется #
|
|
# 20% выборки для валидации результатов. #
|
|
# После обучения проводится проверка работоспособности #
|
|
# модели на тестовой выборке (отдельный файл данных) #
|
|
# -------------------------------------------------------#
|
|
# Импорт библиотек
|
|
import os
|
|
import pandas as pd
|
|
import numpy as np
|
|
import tensorflow as tf
|
|
from tensorflow import keras
|
|
import matplotlib.pyplot as plt
|
|
import MetaTrader5 as mt5
|
|
|
|
# Подключаемся к терминалу MetaTrader 5
|
|
if not mt5.initialize():
|
|
print("initialize() failed, error code =",mt5.last_error())
|
|
quit()
|
|
# Запрашиваем путь в "песочницу"
|
|
path=os.path.join(mt5.terminal_info().data_path,r'MQL5\Files')
|
|
mt5.shutdown()
|
|
# Загрузка обучающей выборки
|
|
filename = os.path.join(path,'study_data.csv')
|
|
data = np.asarray( pd.read_table(filename,
|
|
sep=',',
|
|
header=None,
|
|
skipinitialspace=True,
|
|
encoding='utf-8',
|
|
float_precision='high',
|
|
dtype=np.float64,
|
|
low_memory=False))
|
|
|
|
# Разделение обучающей выборки на исходные данные и цели
|
|
inputs=data.shape[1]-2
|
|
targerts=2
|
|
train_data=data[:,0:inputs]
|
|
train_target=data[:,inputs:]
|
|
|
|
# Созданиие модели нейронной сети
|
|
model = keras.Sequential([keras.layers.InputLayer(input_shape=inputs),
|
|
# Наполнить модель описанием нейронных слоёв
|
|
])
|
|
model.compile(optimizer='Adam',
|
|
loss='mean_squared_error',
|
|
metrics=['accuracy'])
|
|
callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=5)
|
|
history = model.fit(train_data, train_target,
|
|
epochs=500, batch_size=1000,
|
|
callbacks=[callback],
|
|
verbose=2,
|
|
validation_split=0.2,
|
|
shuffle=True)
|
|
|
|
# Сохранение обученной модели
|
|
model.save(os.path.join(path,'model.h5'))
|
|
|
|
# Отрисовка результатов обучениия модели
|
|
plt.plot(history.history['loss'], label='Train')
|
|
plt.plot(history.history['val_loss'], label='Validation')
|
|
plt.ylabel('$MSE$ $Loss$')
|
|
plt.xlabel('$Epochs$')
|
|
plt.title('Dinamic of Models train')
|
|
plt.legend(loc='upper right')
|
|
|
|
plt.figure()
|
|
plt.plot(history.history['accuracy'], label='Train')
|
|
plt.plot(history.history['val_accuracy'], label='Validation')
|
|
plt.ylabel('$Accuracy$')
|
|
plt.xlabel('$Epochs$')
|
|
plt.title('Dinamic of Models train')
|
|
plt.legend(loc='lower right')
|
|
|
|
# Загрузка тестовой выборки
|
|
test_filename = os.path.join(path,'test_data.csv')
|
|
test = np.asarray( pd.read_table(test_filename,
|
|
sep=',',
|
|
header=None,
|
|
skipinitialspace=True,
|
|
encoding='utf-8',
|
|
float_precision='high',
|
|
dtype=np.float64,
|
|
low_memory=False))
|
|
|
|
# Разделение тестовой выборки на исходные данные и цели
|
|
test_data=test[:,0:inputs]
|
|
test_target=test[:,inputs:]
|
|
|
|
# Проверка результатов модели на тестовой выборке
|
|
test_loss, test_acc = model.evaluate(test_data, test_target)
|
|
# Вывод результатов тестирования в журнал
|
|
print('Model in test')
|
|
print('Test accuracy:', test_acc)
|
|
print('Test loss:', test_loss)
|
|
|
|
# Вывод созданных графиков
|
|
plt.show() |