Selam!
Ekonomi zor olunca herkes şans oyunlarına yöneliyor. Ben de yapay zeka ile On Numara'da bir şeyler çözelim dedim. Haftalık verilerden makine öğrenmesi modeli geliştirdim.
Özetle : Deep Q-Network (DQN) kullanarak, geçmiş verileri öğrenir ve bu verilerden yola çıkarak bir loto tahmin modeli oluşturur.
Kod çalışmadan önce
pip install pandas numpy tensorflow scikit-learn matplotlib
.csv yolunu düzenle
Bu model kesin sonuç garanti etmez
Veri örneği:
şimdi kodlarımızla modelimizi eğitip kaydedelim bu ko modeli eğitir sonra kaydedilmiş model ile tahmin yapar
Örnek çıktısı:
Ekonomi zor olunca herkes şans oyunlarına yöneliyor. Ben de yapay zeka ile On Numara'da bir şeyler çözelim dedim. Haftalık verilerden makine öğrenmesi modeli geliştirdim.
Özetle : Deep Q-Network (DQN) kullanarak, geçmiş verileri öğrenir ve bu verilerden yola çıkarak bir loto tahmin modeli oluşturur.
ÖNEMLİ NOT:
Kod çalışmadan öncepip install pandas numpy tensorflow scikit-learn matplotlib
.csv yolunu düzenle
Bu model kesin sonuç garanti etmez
Veri örneği:
Kod:
28.06.2024 5 8 9 11 12 14 20 29 31 36 40 45 50 54 57 59 61 62 66 73 77 78
...
23.01.2006 4 7 13 22 31 33 35 39 42 43 44 45 48 53 58 60 65 69 74 78 79 80
16.01.2006 3 4 6 9 10 12 16 18 25 26 37 48 50 52 58 59 65 67 76 77 78 79
09.01.2006 1 3 6 7 14 18 21 26 36 39 41 46 52 53 54 57 58 61 63 67 68 70
02.01.2006 1 10 12 13 15 17 23 26 30 31 33 39 43 46 56 61 62 67 68 71 73 80
şimdi kodlarımızla modelimizi eğitip kaydedelim bu ko modeli eğitir sonra kaydedilmiş model ile tahmin yapar
Python:
import os
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras import Model, layers
from collections import deque
import random
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error
import math
import time
import csv
# 1. VERİ YÜKLEME
data_path = 'sonuc.csv' #değiştir
data = pd.read_csv(data_path, header=None, names=['Tarih', 'Sonuçlar'])
data['Tarih'] = pd.to_datetime(data['Tarih'], format='%d.%m.%Y')
# 2. VERİ İŞLEME
for i in range(1, 81):
data[f'num_{i}'] = data['Sonuçlar'].apply(lambda x: 1 if str(i) in x.split() else 0)
data['kazanan_numara'] = data['Sonuçlar'].apply(lambda x: np.random.choice(list(map(int, x.split()))))
X = data.drop(columns=['Tarih', 'Sonuçlar', 'kazanan_numara'])
y = data['kazanan_numara']
# 3. MODEL SINIFI
class DQN(Model):
def __init__(self, action_size):
super(DQN, self).__init__()
self.d1 = layers.Dense(1024, activation='relu')
self.d2 = layers.Dense(512, activation='relu')
self.d3 = layers.Dense(256, activation='relu')
self.d4 = layers.Dense(128, activation='relu')
self.d5 = layers.Dense(64, activation='relu')
self.d6 = layers.Dense(32, activation='relu')
self.d7 = layers.Dense(action_size, activation='linear')
def call(self, x):
x = self.d1(x)
x = self.d2(x)
x = self.d3(x)
x = self.d4(x)
x = self.d5(x)
x = self.d6(x)
return self.d7(x)
# 4. DQN AGENT SINIFI
class DQNAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=2000)
self.gamma = 0.95
self.epsilon = 1.0
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.model = self._build_model()
self.target_model = self._build_model()
self.update_target_model()
def _build_model(self):
model = DQN(self.action_size)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=self.learning_rate), loss='mse')
return model
def update_target_model(self):
self.target_model.set_weights(self.model.get_weights())
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
# Keşif (exploration) veya tahmin (exploitation)
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(state, verbose=0)
return np.argmax(act_values[0])
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = self.model.predict(state, verbose=0)
if done:
target[0][action] = reward
else:
target[0][action] = reward + self.gamma * np.amax(self.target_model.predict(next_state, verbose=0)[0])
self.model.fit(state, target, epochs=1, verbose=0)
def get_lottery_prediction(self, state, num_predictions=3, num_numbers=10):
predictions = []
for _ in range(num_predictions):
act_values = self.model.predict(state, verbose=0)
top_indices = np.argsort(act_values[0])[-num_numbers:]
predictions.append(sorted(top_indices + 1))
return predictions
# 5. EĞİTİM VE MODEL KAYDETME
def train_and_save_model():
state_size = X.shape[1]
action_size = 80
agent = DQNAgent(state_size, action_size)
episodes = 1000
batch_size = 32
mse_list, mae_list, rmse_list = [], [], []
start_time = time.time()
save_dir = 'saved_model'
os.makedirs(save_dir, exist_ok=True)
with open('metrics.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=['Episode', 'MSE', 'MAE', 'RMSE'])
writer.writeheader()
for e in range(episodes):
state = X.iloc[0].values.reshape(1, -1)
for time_step in range(len(X)):
action = agent.act(state)
reward = 1 if action == y.iloc[time_step] else -1
next_state = X.iloc[(time_step + 1) % len(X)].values.reshape(1, -1)
done = time_step == (len(X) - 1)
agent.remember(state, action, reward, next_state, done)
state = next_state
if done:
agent.update_target_model()
print(f"episode: {e}/{episodes}, skor: {time_step}, keşif oranı(e): {agent.epsilon:.2f}")
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
if e % 10 == 0:
y_pred = []
for state in X.values:
state = state.reshape(1, -1)
y_pred.append(agent.act(state))
mse = mean_squared_error(y, y_pred)
mae = mean_absolute_error(y, y_pred)
rmse = math.sqrt(mse)
mse_list.append(mse)
mae_list.append(mae)
rmse_list.append(rmse)
print(f"Episode: {e}, MSE: {mse:.2f}, MAE: {mae:.2f}, RMSE: {rmse:.2f}")
writer.writerow({'Episode': e, 'MSE': mse, 'MAE': mae, 'RMSE': rmse})
if e % 50 == 0:
agent.model.save(os.path.join(save_dir, f"model_e{e}.keras"))
model_json_path = os.path.join(save_dir, f"model_e{e}_json")
os.makedirs(model_json_path, exist_ok=True)
with open(os.path.join(model_json_path, 'model.json'), 'w') as json_file:
json_file.write(agent.model.to_json())
agent.model.save_weights(os.path.join(model_json_path, 'model_weights.weights.h5'))
end_time = time.time()
print(f"Toplam Eğitim Süresi: {end_time - start_time:.2f} saniye")
agent.model.save(os.path.join(save_dir, 'final_model.keras'))
plt.figure(figsize=(12, 5))
plt.subplot(1, 3, 1)
plt.plot(mse_list)
plt.xlabel('Episode (x10)')
plt.ylabel('MSE')
plt.subplot(1, 3, 2)
plt.plot(mae_list)
plt.xlabel('Episode (x10)')
plt.ylabel('MAE')
plt.subplot(1, 3, 3)
plt.plot(rmse_list)
plt.xlabel('Episode (x10)')
plt.ylabel('RMSE')
plt.tight_layout()
plt.savefig('model_performance.png')
return agent
# 6. MODEL YÜKLEME VE TAHMİN
def load_and_predict():
final_model_path = os.path.join('saved_model', 'final_model.keras')
state_size = X.shape[1]
action_size = 80
agent = DQNAgent(state_size, action_size)
agent.model = tf.keras.models.load_model(final_model_path)
state = X.iloc[-1].values.reshape(1, -1)
predictions = agent.get_lottery_prediction(state)
print("\n On Numara Tahminleri:")
for i, pred in enumerate(predictions, 1):
print(f"Kolon {i}: {pred}")
return predictions
# 7. ANA FONKSİYON
def main():
trained_agent = train_and_save_model()
load_and_predict()
if __name__ == "__main__":
main()
Örnek çıktısı:
Bash:
episode: 0/1000, score: 42, e: 0.99
Episode: 0, MSE: 45.67, MAE: 3.21, RMSE: 6.75
episode: 10/1000, score: 38, e: 0.95
Episode: 10, MSE: 42.13, MAE: 3.05, RMSE: 6.49
100 episodes completed.
Episode: 100, MSE: 28.45, MAE: 2.34, RMSE: 5.33
Training duration: 127.45 seconds
Bash:
On Numara Tahminleri:
Kolon 1: [3, 7, 12, 23, 34, 45, 56, 67, 72, 80]
Kolon 2: [5, 11, 22, 33, 44, 55, 66, 71, 75, 79]
Kolon 3: [4, 9, 18, 29, 39, 48, 59, 68, 76, 78]
Ekler
Son düzenleme: