23 Ιανουαρίου, 1970

ROULETTA -2

 import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
import random

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout

N = 10

input_data = np.tile(np.linspace(0.01, 0.8, 80), (N, 1))

input_data_1 = input_data[:, 0:20]
input_data_2 = input_data[:, 20:40]
input_data_3 = input_data[:, 40:60]
input_data_4 = input_data[:, 60:80]

output_data = np.array([
[0.06, 0.15, 0.18, 0.22, 0.26, 0.28, 0.3, 0.34, 0.36, 0.47, 0.55, 0.57, 0.59, 0.65, 0.66, 0.68, 0.7, 0.74, 0.76, 0.8],
[0.04, 0.05, 0.07, 0.13, 0.14, 0.2, 0.24, 0.27, 0.28, 0.31, 0.38, 0.41, 0.42, 0.43, 0.48, 0.52, 0.57, 0.63, 0.68, 0.75],
[0.08, 0.11, 0.13, 0.23, 0.24, 0.25, 0.28, 0.33, 0.37, 0.39, 0.4, 0.42, 0.44, 0.46, 0.5, 0.61, 0.66, 0.69, 0.78, 0.8],
[0.07, 0.08, 0.1, 0.15, 0.19, 0.21, 0.24, 0.29, 0.3, 0.31, 0.33, 0.36, 0.4, 0.44, 0.46, 0.54, 0.56, 0.59, 0.67, 0.76],
[0.06, 0.08, 0.09, 0.11, 0.12, 0.13, 0.2, 0.27, 0.29, 0.3, 0.33, 0.34, 0.39, 0.42, 0.47, 0.48, 0.49, 0.64, 0.67, 0.73],
[0.01, 0.08, 0.1, 0.11, 0.14, 0.15, 0.18, 0.24, 0.27, 0.29, 0.33, 0.42, 0.43, 0.47, 0.5, 0.58, 0.64, 0.67, 0.73, 0.75],
[0.01, 0.06, 0.11, 0.15, 0.17, 0.18, 0.2, 0.21, 0.22, 0.27, 0.35, 0.36, 0.38, 0.39, 0.68, 0.7, 0.72, 0.77, 0.79, 0.8],
[0.01, 0.09, 0.12, 0.17, 0.22, 0.25, 0.28, 0.29, 0.32, 0.34, 0.37, 0.43, 0.51, 0.57, 0.58, 0.63, 0.64, 0.7, 0.78, 0.8],
[0.03, 0.07, 0.19, 0.24, 0.27, 0.3, 0.36, 0.38, 0.41, 0.42, 0.48, 0.53, 0.57, 0.59, 0.68, 0.69, 0.7, 0.77, 0.79, 0.8],
[0.06, 0.08, 0.09, 0.11, 0.12, 0.13, 0.2, 0.27, 0.29, 0.3, 0.33, 0.34, 0.39, 0.42, 0.47, 0.48, 0.49, 0.64, 0.67, 0.73]
])

output_data_1 = [row[(row >= 0.01) & (row <= 0.20)] for row in output_data]
output_data_2 = [row[(row >= 0.21) & (row <= 0.40)] for row in output_data]
output_data_3 = [row[(row >= 0.41) & (row <= 0.60)] for row in output_data]
output_data_4 = [row[(row >= 0.61) & (row <= 0.80)] for row in output_data]

time_series_1 = np.hstack(output_data_1)
time_series_2 = np.hstack(output_data_2)
time_series_3 = np.hstack(output_data_3)
time_series_4 = np.hstack(output_data_4)

#---------------------------------------------------------------------------------------------------

time_series_1 = np.hstack(output_data_1)
n_steps_1 = 5
lstm_units_1 = 150
dense_units_1 = 25
epochs_1 = 50
optimizer_1 = "adam"

def prepare_data(series, n_steps_1):
X, y = [], []
for i in range(len(series) - n_steps_1):
X.append(series[i:i + n_steps_1])
y.append(series[i + n_steps_1])
return np.array(X), np.array(y)

X1, y1 = prepare_data(time_series_1, n_steps_1)
X1 = X1.reshape((X1.shape[0], X1.shape[1], 1))

model1 = Sequential([
LSTM(lstm_units_1, activation='relu', input_shape=(n_steps_1, 1)),
Dense(dense_units_1, activation='relu'),
Dense(1)
])

model1.compile(optimizer=optimizer_1, loss='mse')
model1.fit(X1, y1, epochs=epochs_1, verbose=0)

def predict_next(model, series, n_steps_1, future=5):
input_seq = series[-n_steps_1:].reshape(1, n_steps_1, 1)
predictions_1 = []
for _ in range(future):
next_val = model.predict(input_seq, verbose=0)[0, 0]
predictions_1.append(next_val)
input_seq = np.roll(input_seq, -1, axis=1)
input_seq[0, -1, 0] = next_val
return predictions_1

predictions_1 = predict_next(model1, time_series_1, n_steps_1)
print(f"Predictions for Time Series 1: {predictions_1}")

#---------------------------------------------------------------------

time_series_2 = np.hstack(output_data_2)
n_steps_2 = 5
lstm_units_2 = 150
dense_units_2 = 25
epochs_2 = 50
optimizer_2 = "adam"

def prepare_data(series, n_steps):
X, y = [], []
for i in range(len(series) - n_steps):
X.append(series[i:i + n_steps])
y.append(series[i + n_steps])
return np.array(X), np.array(y)

X1, y1 = prepare_data(time_series_2, n_steps_2)
X1 = X1.reshape((X1.shape[0], X1.shape[1], 1))

model2 = Sequential([
LSTM(lstm_units_2, activation='relu', input_shape=(n_steps_2, 1)),
Dense(dense_units_2, activation='relu'),
Dense(1)
])

model2.compile(optimizer=optimizer_2, loss='mse')
model2.fit(X1, y1, epochs=epochs_2, verbose=0)

def predict_next(model, series, n_steps_2, future=5):
input_seq = series[-n_steps_2:].reshape(1, n_steps_2, 1)
predictions_2 = []
for _ in range(future):
next_val = model.predict(input_seq, verbose=0)[0, 0]
predictions_2.append(next_val)
input_seq = np.roll(input_seq, -1, axis=1)
input_seq[0, -1, 0] = next_val
return predictions_2

predictions_2 = predict_next(model2, time_series_2, n_steps_2)
print(f"Predictions for Time Series 2: {predictions_2}")

#---------------------------------------------------------------------

time_series_3 = np.hstack(output_data_3)
n_steps_3 = 5
lstm_units_3 = 150
dense_units_3 = 25
epochs_3 = 50
optimizer_3 = "adam"

def prepare_data(series, n_steps):
X, y = [], []
for i in range(len(series) - n_steps):
X.append(series[i:i + n_steps])
y.append(series[i + n_steps])
return np.array(X), np.array(y)

X1, y1 = prepare_data(time_series_3, n_steps_3)
X1 = X1.reshape((X1.shape[0], X1.shape[1], 1))

model3 = Sequential([
LSTM(lstm_units_3, activation='relu', input_shape=(n_steps_2, 1)),
Dense(dense_units_3, activation='relu'),
Dense(1)
])

model3.compile(optimizer=optimizer_3, loss='mse')
model3.fit(X1, y1, epochs=epochs_3, verbose=0)

def predict_next(model, series, n_steps_3, future=5):
input_seq = series[-n_steps_3:].reshape(1, n_steps_3, 1)
predictions_3 = []
for _ in range(future):
next_val = model.predict(input_seq, verbose=0)[0, 0]
predictions_3.append(next_val)
input_seq = np.roll(input_seq, -1, axis=1)
input_seq[0, -1, 0] = next_val
return predictions_3

predictions_3 = predict_next(model3, time_series_3, n_steps_2)
print(f"Predictions for Time Series 3: {predictions_3}")

#---------------------------------------------------------------------

time_series_4 = np.hstack(output_data_4)
n_steps_4 = 5
lstm_units_4 = 150
dense_units_4 = 25
epochs_4 = 50
optimizer_4 = "adam"

def prepare_data(series, n_steps_4):
X, y = [], []
for i in range(len(series) - n_steps_4):
X.append(series[i:i + n_steps_4])
y.append(series[i + n_steps_4])
return np.array(X), np.array(y)

X1, y1 = prepare_data(time_series_4, n_steps_4)
X1 = X1.reshape((X1.shape[0], X1.shape[1], 1))

model4 = Sequential([
LSTM(lstm_units_4, activation='relu', input_shape=(n_steps_4, 1)),
Dense(dense_units_4, activation='relu'),
Dense(1)
])

model4.compile(optimizer=optimizer_4, loss='mse')
model4.fit(X1, y1, epochs=epochs_4, verbose=0)

def predict_next(model, series, n_steps_4, future=5):
input_seq = series[-n_steps_4:].reshape(1, n_steps_4, 1)
predictions_4 = []
for _ in range(future):
next_val = model.predict(input_seq, verbose=0)[0, 0]
predictions_4.append(next_val)
input_seq = np.roll(input_seq, -1, axis=1)
input_seq[0, -1, 0] = next_val
return predictions_4

predictions_4 = predict_next(model4, time_series_4, n_steps_4)
print(f"Predictions for Time Series 2: {predictions_4}")

#-------------------------------------------------------------


N = 10
timesteps = 4
features = 20

input_data = np.tile(np.linspace(0.01, 0.8, 80), (N, 1)).reshape(N, timesteps, features)

model5 = Sequential([
LSTM(64, return_sequences=True, input_shape=(timesteps, features)),
LSTM(32), # Δεύτερο επίπεδο LSTM με 32 μονάδες
Dense(20, activation='linear')
])

model5.compile(optimizer='adam', loss='mse')
model5.fit(input_data, output_data, epochs=50, batch_size=1, verbose=0)

test_sample = np.random.rand(1, timesteps, features) # Τυχαίο νέο δείγμα εισόδου
predicted_sequence = model5.predict(test_sample)

print("Πρόβλεψη:", predicted_sequence)


#----------------------------------------------------------------------

max_output_length = max(len(seq) for seq in output_data_1)

def pad_with_moving_avg(seq, target_length):
if len(seq) == 0:
return np.zeros(target_length)

moving_avg = np.mean(seq[-3:]) if len(seq) >= 3 else np.mean(seq) # Μέσος όρος τελευταίων 3 τιμών
padded_seq = np.pad(seq, (0, target_length - len(seq)), mode='constant', constant_values=moving_avg)
return padded_seq

y_padded = np.array([pad_with_moving_avg(seq, max_output_length) for seq in output_data_1])

X_train = y_padded[:, :-1].reshape(N, max_output_length - 1, 1)
y_train = y_padded[:, 1:].reshape(N, max_output_length - 1, 1)

model6 = Sequential([
LSTM(64, activation='relu', return_sequences=True, input_shape=(max_output_length - 1, 1)),
LSTM(32, activation='relu', return_sequences=True),
Dense(16, activation='relu'),
Dense(1, activation='linear')
])

model6.compile(optimizer='adam', loss='mse', metrics=['mae'])
model6.fit(X_train, y_train, epochs=50, batch_size=2, verbose=0)

predictions_5 = model6.predict(X_train)
print("Προβλέψεις για την επόμενη ακολουθία:", predictions_5[0][0])


#--------------------------------------------------------------------------

def pad_with_moving_avg(sequences, max_length):
padded_sequences = []

for seq in sequences:
if len(seq) == 0:
padded_sequences.append(np.zeros(max_length, dtype=np.float32))
elif len(seq) >= max_length:
padded_sequences.append(seq[:max_length])
else:
moving_avg = np.mean(seq[-3:]) if len(seq) >= 3 else np.mean(seq)
padded_seq = np.pad(seq, (0, max_length - len(seq)), mode='constant', constant_values=moving_avg)
padded_sequences.append(padded_seq)

return np.array(padded_sequences, dtype=np.float32)


# Εύρεση του μέγιστου μήκους
max_output_length = max(len(seq) for seq in output_data_1)

# Padding σε όλες τις σειρές εξόδου
y_padded = pad_with_moving_avg(output_data_1, max_output_length)

# Αναδιαμόρφωση για το LSTM
X_train = y_padded[:, :-1].reshape(N, max_output_length - 1, 1)
y_train = y_padded[:, 1:].reshape(N, max_output_length - 1, 1)

model7 = Sequential([
LSTM(64, activation='relu', return_sequences=True, input_shape=(max_output_length - 1, 1)),
LSTM(32, activation='relu', return_sequences=True),
Dense(16, activation='relu'),
Dense(1, activation='linear')
])

model7.compile(optimizer='adam', loss='mse', metrics=['mae'])
model7.fit(X_train, y_train, epochs=50, batch_size=2, verbose=0)

# Διορθωμένο Padding στο X_test
X_test = pad_with_moving_avg(output_data_1, max_output_length - 1)
X_test = X_test.reshape(N, max_output_length - 1, 1)

# Πρόβλεψη
predictions_6 = model7.predict(X_test, batch_size=32)

print("πρόβλεψη:", predictions_6[0][0])