Пользуюсь этим сайтом впервые. Помогите, пожалуйста исправить код. Создаю нейросеть впервые. И не понимаю, что значат ошибки, высвечивающиеся при попытке запуска кода. Вот часть ошибок:
D:\Python\VospolnenyeDannyh\main.py:9: SyntaxWarning: "\i" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\i"? A raw string is also an option.
file_path = 'C:\for_educate\ishodnye1.xlsx'
Traceback (most recent call last):
File "D:\Python\VospolnenyeDannyh\main.py", line 3, in <module>
from keras.models import Sequential
File "D:\Python\VospolnenyeDannyh\.venv\Lib\site-packages\keras\__init__.py", line 7, in <module>
from keras import _tf_keras as _tf_keras
File "D:\Python\VospolnenyeDannyh\.venv\Lib\site-packages\keras\_tf_keras\__init__.py", line 1, in <module>
from keras._tf_keras import keras
File "D:\Python\VospolnenyeDannyh\.venv\Lib\site-packages\keras\_tf_keras\keras\__init__.py", line 7, in <module>
from keras import activations as activations
Сам код:
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
# Загрузка данных из Excel
file_path = 'path_to_your_file.xlsx'
data = pd.read_excel(file_path)
# Дата во формате DD-MM-YYYY HH:MM, преобразуем в datetime
data['datetime'] = pd.to_datetime(data['datetime'], format='%d-%m-%Y %H:%M') # Указываем нужный формат
data.set_index('datetime', inplace=True)
data = data.resample('H').mean() # Ресемплинг данных по часам
data.fillna(method='ffill', inplace=True) # Заполнение пропусков
# Преобразование данных в формат для нейросети
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(data)
# Функция для создания последовательностей
def create_sequences(data, time_step=1):
X, y = [], []
for i in range(len(data) - time_step):
X.append(data[i:(i + time_step), 0])
y.append(data[i + time_step, 0])
return np.array(X), np.array(y)
# Выбор временного шага
time_step = 24 # 24 часа (1 день)
X, y = create_sequences(scaled_data, time_step)
# Разделение данных на обучающую и тестовую выборки
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Изменение формы данных для LSTM [samples, time steps, features]
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# Создание модели нейросети
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
LSTM(50),
Dense(1) # Один выход, который будем предсказывать
])
model.compile(optimizer='adam', loss='mean_squared_error')
# Обучение модели
model.fit(X_train, y_train, epochs=50, batch_size=32)
# Прогнозирование на следующие 180 дней
def predict_next_days(model, data, time_step, days=180):
predictions = []
current_step = data[-time_step:].reshape(1, time_step, 1)
for _ in range(days * 24): # 180 дней * 24 часа
next_pred = model.predict(current_step)[0][0]
predictions.append(next_pred)
# Обновим текущий шаг для следующего предсказания
current_step = np.append(current_step[:, 1:, :], [[next_pred]], axis=1)
return np.array(predictions)
# Осуществляем прогнозирование
future_predictions = predict_next_days(model, scaled_data, time_step)
# Возвращаемся к исходному масштабу
future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1))
# Генерация временных меток для будущих прогнозов
last_timestamp = data.index[-1]
future_dates = [last_timestamp + pd.Timedelta(hours=i) for i in range(1, len(future_predictions) + 1)]
# Создание DataFrame для сохранения в Excel
results = pd.DataFrame({
'Datetime': future_dates,
'PredictedConsumption': future_predictions.flatten()
})
# Сохранение в новый Excel файл
result_file_path = 'predicted_consumption.xlsx'
results.to_excel(result_file_path, index=False)
print(f'Прогноз сохранен в файл: {result_file_path}')
Файл exel выглядит таким образом и продолжается до 4тыс стр.
datetime consumption
01.08.2025 1:00 165,336192
01.08.2025 2:00 145,272396
01.08.2025 3:00 141,066372
01.08.2025 04:00 131,405772
01.08.2025 05:00 125,29632
01.08.2025 06:00 118,825488
01.08.2025 07:00 124,840272
01.08.2025 08:00 141,139692
01.08.2025 09:00 168,876024
01.08.2025 10:00 207,933048
01.08.2025 11:00 228,316272
01.08.2025 12:00 232,615392
01.08.2025 13:00 237,171
01.08.2025 14:00 238,704948
01.08.2025 15:00 243,23286
01.08.2025 16:00 252,414804
01.08.2025 17:00 245,78964
01.08.2025 18:00 233,256168
01.08.2025 19:00 223,759296
01.08.2025 20:00 207,799248
01.08.2025 21:00 201,520044
01.08.2025 22:00 190,7724
01.08.2025 23:00 177,551808
02.08.2025 00:00 162,096684
02.08.2025 01:00 144,607032
02.08.2025 02:00 129,900732
02.08.2025 03:00 123,466596
02.08.2025 04:00 120,281784
02.08.2025 05:00 116,012436
02.08.2025 06:00 110,279484
02.08.2025 07:00 118,414128
02.08.2025 08:00 130,253376
02.08.2025 09:00 150,843828
02.08.2025 10:00 180,792696
02.08.2025 11:00 202,621752
02.08.2025 12:00 225,342708
02.08.2025 13:00 231,007056
02.08.2025 14:00 237,945516
02.08.2025 15:00 237,80874
02.08.2025 16:00 236,185716
02.08.2025 17:00 246,816036
02.08.2025 18:00 232,81692
02.08.2025 19:00 222,275856
02.08.2025 20:00 216,1902
02.08.2025 21:00 215,6562
02.08.2025 22:00 194,363772
02.08.2025 23:00 183,691008
03.08.2025 00:00 163,603248
03.08.2025 01:00 152,182296