import numpy as np import pandas as pd def main(): Load your CSV data data =…
- User
import numpy as np import pandas as pd
def main(): # Load your CSV data data = pd.read_csv('/content/drive/MyDrive/BIST_10/MDP_IRL/MLB/AKBNK.csv') # Replace 'your_data.csv' with your actual file name
# Number of states and actions n_states = 15 # From your data (states are 0 to 14) n_actions = 3 # From your data (actions are 0, 1, 2) # Convert data to numpy array state_action_nextstate = data[['State', 'Action', 'Next_State']].to_numpy() # Process data into trajectories trajectory_length = 20 n_observations = state_action_nextstate.shape[0] n_full_trajectories = n_observations // trajectory_length trajectories = [] for i in range(n_full_trajectories): traj = state_action_nextstate[i*trajectory_length : (i+1)*trajectory_length] trajectories.append(traj) # Add remaining data as the last trajectory if n_observations % trajectory_length != 0: last_traj = state_action_nextstate[n_full_trajectories * trajectory_length:] # Pad the last trajectory to length 20 last_step = last_traj[-1] padding_length = trajectory_length - last_traj.shape[0] padding = np.tile(last_step, (padding_length, 1)) last_traj_padded = np.vstack((last_traj, padding)) trajectories.append(last_traj_padded) # Convert list of trajectories to numpy array trajectories = np.array(trajectories) # Build transition probability tensor transition_counts = np.zeros((n_states, n_actions, n_states)) for s, a, s_next in state_action_nextstate: transition_counts[int(s), int(a), int(s_next)] += 1 # Add smoothing to avoid zero probabilities smoothing = 1e-5 transition_counts += smoothing transition_probability = np.zeros((n_states, n_actions, n_states)) for s in range(n_states): for a in range(n_actions): total = np.sum(transition_counts[s, a, :]) transition_probability[s, a, :] = transition_counts[s, a, :] / total # Create feature matrix (one-hot encoding) feature_matrix = np.eye(n_states) # Set discount factor discount = 0.9 # Set algorithm parameters epochs = 100 learning_rate = 0.01 # Run MaxEnt IRL reward = irl(feature_matrix, n_actions, discount, transition_probability, trajectories, epochs, learning_rate) print("Learned reward function:") print(reward)def irl(feature_matrix, n_actions, discount, transition_probability, trajectories, epochs, learning_rate): """ Find the reward function for the given trajectories. """ n_states, d_states = feature_matrix.shape
# Initialize weights. alpha = np.random.uniform(size=(d_states,)) # Calculate the feature expectations \tilde{phi}. feature_expectations = find_feature_expectations(feature_matrix, trajectories) # Gradient descent on alpha. for i in range(epochs): r = feature_matrix.dot(alpha) expected_svf = find_expected_svf(n_states, r, n_actions, discount, transition_probability, trajectories) grad = feature_expectations - feature_matrix.T.dot(expected_svf) alpha += learning_rate * grad return feature_matrix.dot(alpha).reshape((n_states,))def find_feature_expectations(feature_matrix, trajectories): """ Find the feature expectations for the given trajectories. """ T = trajectories.shape[0] # Number of trajectories feature_expectations = np.zeros(feature_matrix.shape[1])
for traj in trajectories: for state, action, next_state in traj: feature_expectations += feature_matrix[int(state)] feature_expectations /= T * trajectories.shape[1] # Normalize over all time steps return feature_expectationsdef find_expected_svf(n_states, r, n_actions, discount, transition_probability, trajectories): """ Find the expected state visitation frequencies. """ # Compute policy using soft value iteration policy = compute_policy(n_states, n_actions, transition_probability, r, discount)
# Initial state probabilities T = trajectories.shape[0] start_state_counts = np.zeros(n_states) for traj in trajectories: start_state = int(traj[0, 0]) start_state_counts[start_state] += 1 p_start_state = start_state_counts / T # Compute expected state visitation frequencies trajectory_length = trajectories.shape[1] expected_svf = np.zeros((n_states, trajectory_length)) expected_svf[:, 0] = p_start_state for t in range(1, trajectory_length): expected_svf[:, t] = 0 for s in range(n_states): for a in range(n_actions): for s_next in range(n_states): expected_svf[s_next, t] += expected_svf[s, t-1] * policy[s, a] * transition_probability[s, a, s_next] return expected_svf.sum(axis=1)def compute_policy(n_states, n_actions, transition_probability, reward, discount): """ Compute the policy using soft value iteration. """ max_iters = 1000 threshold = 1e-5 V = np.zeros(n_states)
for i in range(max_iters): V_prev = V.copy() Q = np.zeros((n_states, n_actions)) for s in range(n_states): for a in range(n_actions): Q[s, a] = np.sum(transition_probability[s, a, :] * (reward + discount * V_prev)) V = np.log(np.sum(np.exp(Q), axis=1)) # Soft value iteration if np.max(np.abs(V - V_prev)) < threshold: break # Compute policy policy = np.zeros((n_states, n_actions)) for s in range(n_states): for a in range(n_actions): Q_sa = np.sum(transition_probability[s, a, :] * (reward + discount * V)) policy[s, a] = np.exp(Q_sa - V[s]) # Subtract V[s] for normalization # Normalize policy policy = policy / np.sum(policy, axis=1, keepdims=True) return policyif name == 'main': main()
Kodu kontrol edebilir misin? Eksik, hatalı ya da değişmesi gereken her yeri titizlikle ele almanı istiyorum.
- Assistant
Elbette, kodunuzu detaylı bir şekilde inceleyerek eksik, hatalı veya iyileştirilmesi gereken noktaları belirteceğim. Aşağıda adım adım analiz ve önerilerimi bulabilirsiniz:
1. Veri Yükleme ve Hazırlık
import numpy as np import pandas as pd def main(): # Load your CSV data data = pd.read_csv('/content/drive/MyDrive/BIST_10/MDP_IRL/MLB/AKBNK.csv') # Replace 'your_data.csv' with your actual file name # Number of states and actions n_states = 15 # From your data (states are 0 to 14) n_actions = 3 # From your data (actions are 0, 1, 2)İnceleme ve Öneriler:
-
Dosya Yolu:
/content/drive/...gibi bir yol kullanıyorsanız, bu genellikle Google Colab ortamına özgüdür. Kodun farklı ortamlarda çalışabilmesi için dosya yolunun dinamik olması veya kullanıcıdan alınması daha esnek olabilir. -
Durum ve Aksiyon Sayıları:
n_statesven_actionsdeğerlerini veri setinden otomatik olarak belirlemek daha dinamik bir çözüm sağlayabilir. Örneğin:n_states = data['State'].nunique() n_actions = data['Action'].nunique()
2. Veri İşleme ve Trajektori Oluşturma
# Convert data to numpy array state_action_nextstate = data[['State', 'Action', 'Next_State']].to_numpy() # Process data into trajectories trajectory_length = 20 n_observations = state_action_nextstate.shape[0] n_full_trajectories = n_observations // trajectory_length trajectories = [] for i in range(n_full_trajectories): traj = state_action_nextstate[i*trajectory_length : (i+1)*trajectory_length] trajectories.append(traj) # Add remaining data as the last trajectory if n_observations % trajectory_length != 0: last_traj = state_action_nextstate[n_full_trajectories * trajectory_length:] # Pad the last trajectory to length 20 last_step = last_traj[-1] padding_length = trajectory_length - last_traj.shape[0] padding = np.tile(last_step, (padding_length, 1)) last_traj_padded = np.vstack((last_traj, padding)) trajectories.append(last_traj_padded) # Convert list of trajectories to numpy array trajectories = np.array(trajectories)İnceleme ve Öneriler:
-
Trajektori Oluşturma:
- Trajektorilerin sabit uzunlukta (
trajectory_length = 20) olması zorunlu değilse, esnek bir yaklaşım benimsemek daha uygun olabilir. - Son trajektoriyi pad etmek yerine, eksik adımları başka bir yöntemle ele almak (örneğin, trajektoriyi sınırlamak veya eksik adımları dikkate almamak) tercih edilebilir.
- Trajektorilerin sabit uzunlukta (
-
Performans:
-
Trajektorilerin oluşturulması sırasında list comprehension kullanmak, kodu daha okunabilir ve potansiyel olarak daha hızlı hale getirebilir:
trajectories = [ state_action_nextstate[i*trajectory_length : (i+1)*trajectory_length] for i in range(n_full_trajectories) ] if n_observations % trajectory_length != 0: last_traj = state_action_nextstate[n_full_trajectories * trajectory_length:] padding_length = trajectory_length - last_traj.shape[0] padding = np.tile(last_traj[-1], (padding_length, 1)) last_traj_padded = np.vstack((last_traj, padding)) trajectories.append(last_traj_padded) trajectories = np.array(trajectories)
-
3. Geçiş Olasılıkları ve Özellik Matrisi
# Build transition probability tensor transition_counts = np.zeros((n_states, n_actions, n_states)) for s, a, s_next in state_action_nextstate: transition_counts[int(s), int(a), int(s_next)] += 1 # Add smoothing to avoid zero probabilities smoothing = 1e-5 transition_counts += smoothing transition_probability = np.zeros((n_states, n_actions, n_states)) for s in range(n_states): for a in range(n_actions): total = np.sum(transition_counts[s, a, :]) transition_probability[s, a, :] = transition_counts[s, a, :] / total # Create feature matrix (one-hot encoding) feature_matrix = np.eye(n_states)İnceleme ve Öneriler:
-
Geçiş Olasılıkları Hesaplama:
-
Döngüler yerine vektörel işlemler kullanarak performansı artırabilirsiniz.
transition_counts = np.zeros((n_states, n_actions, n_states)) for s, a, s_next in state_action_nextstate: transition_counts[int(s), int(a), int(s_next)] += 1 # Smoothing transition_counts += smoothing # Normalization transition_probability = transition_counts / transition_counts.sum(axis=2, keepdims=True)
-
-
Özellik Matrisi:
- One-hot encoding kullanmak uygun olabilir, ancak durum özelliklerinin daha zengin olduğu senaryolarda farklı özellik temsilleri düşünmek faydalı olabilir.
4. IRL Fonksiyonları ve Optimizasyon
# Set discount factor discount = 0.9 # Set algorithm parameters epochs = 100 learning_rate = 0.01 # Run MaxEnt IRL reward = irl(feature_matrix, n_actions, discount, transition_probability, trajectories, epochs, learning_rate) print("Learned reward function:") print(reward)5. IRL Fonksiyonları Detaylı İnceleme
a. IRL Fonksiyonu
def irl(feature_matrix, n_actions, discount, transition_probability, trajectories, epochs, learning_rate): """ Find the reward function for the given trajectories. """ n_states, d_states = feature_matrix.shape # Initialize weights. alpha = np.random.uniform(size=(d_states,)) # Calculate the feature expectations \tilde{phi}. feature_expectations = find_feature_expectations(feature_matrix, trajectories) # Gradient descent on alpha. for i in range(epochs): r = feature_matrix.dot(alpha) expected_svf = find_expected_svf(n_states, r, n_actions, discount, transition_probability, trajectories) grad = feature_expectations - feature_matrix.T.dot(expected_svf) alpha += learning_rate * grad return feature_matrix.dot(alpha).reshape((n_states,))İnceleme ve Öneriler:
-
Aşama Sayısı ve Öğrenme Hızı:
epochsvelearning_ratedeğerleri problemden probleme değişebilir. Bu parametrelerin dinamik ayarlanabilmesi veya farklı değerlerle denemeler yapılması tavsiye edilir.
-
Konverjans Takibi:
-
Optimizasyon sürecinde kayıp (loss) ya da gradyan normu gibi metrikler takip edilerek konverjansın izlenmesi faydalı olabilir. Bu, erken durdurma (early stopping) gibi stratejilerin uygulanmasını sağlar.
for i in range(epochs): r = feature_matrix.dot(alpha) expected_svf = find_expected_svf(n_states, r, n_actions, discount, transition_probability, trajectories) grad = feature_expectations - feature_matrix.T.dot(expected_svf) alpha += learning_rate * grad # Konverjans kontrolü if np.linalg.norm(grad) < 1e-6: print(f"Converged at epoch {i}") break
-
b. Özellik Beklentileri Hesaplama
def find_feature_expectations(feature_matrix, trajectories): """ Find the feature expectations for the given trajectories. """ T = trajectories.shape[0] # Number of trajectories feature_expectations = np.zeros(feature_matrix.shape[1]) for traj in trajectories: for state, action, next_state in traj: feature_expectations += feature_matrix[int(state)] feature_expectations /= T * trajectories.shape[1] # Normalize over all time steps return feature_expectationsİnceleme ve Öneriler:
-
Veri Yapısı:
-
Eğer
trajectoriesNumpy dizisi şeklindeyse, daha verimli hesaplama yöntemleri kullanılabilir.feature_expectations = feature_matrix[trajectories[:,:,0].astype(int)].sum(axis=0) feature_expectations /= (trajectories.shape[0] * trajectories.shape[1])
-
-
Hatalı İndeksleme:
trajectories[:,:,0]ilestateindeksini almak, sütun adlarının sırasına bağlıdır. Daha güvenli olması için sütun adları üzerinden erişim sağlanabilir.
c. Beklenen Durum Ziyaret Frekanslarının (SVF) Hesaplanması
def find_expected_svf(n_states, r, n_actions, discount, transition_probability, trajectories): """ Find the expected state visitation frequencies. """ # Compute policy using soft value iteration policy = compute_policy(n_states, n_actions, transition_probability, r, discount) # Initial state probabilities T = trajectories.shape[0] start_state_counts = np.zeros(n_states) for traj in trajectories: start_state = int(traj[0, 0]) start_state_counts[start_state] += 1 p_start_state = start_state_counts / T # Compute expected state visitation frequencies trajectory_length = trajectories.shape[1] expected_svf = np.zeros((n_states, trajectory_length)) expected_svf[:, 0] = p_start_state for t in range(1, trajectory_length): expected_svf[:, t] = 0 for s in range(n_states): for a in range(n_actions): for s_next in range(n_states): expected_svf[s_next, t] += expected_svf[s, t-1] * policy[s, a] * transition_probability[s, a, s_next] return expected_svf.sum(axis=1)İnceleme ve Öneriler:
-
Performans İyileştirme:
-
Üçlü döngüler (for s, for a, for s_next) büyük ölçekli problemler için çok yavaş olabilir. Matris çarpımları ve vektörleştirme teknikleri kullanarak bu kısmı hızlandırabilirsiniz.
for t in range(1, trajectory_length): expected_svf[:, t] = 0 for s in range(n_states): expected_svf[:, t] += expected_svf[s, t-1] * np.sum(policy[s, :] * transition_probability[s, :, :], axis=(0,1))Ancak bu örnek de tam olarak doğru olmayabilir. Daha iyi bir yaklaşım, tüm matriks operasyonlarını kullanmaktır. Örneğin:
for t in range(1, trajectory_length): expected_svf[:, t] = (policy * transition_probability).sum(axis=(1,2)) * expected_svf[:, t-1]Ancak, doğru matris boyutlarını sağlamak için dikkatli olmak gerekir.
-
-
İlk Durum Olasılıkları:
- Başlangıç durum dağılımını veri setinden alıyorsunuz, bu doğru. Ancak tüm trajektoriler aynı uzunlukta olduğundan, bu yaklaşım uygundur. Farklı uzunluklardaki trajektoriler için ek düzenlemeler gerekebilir.
d. Politika Hesaplama (Soft Value Iteration)
def compute_policy(n_states, n_actions, transition_probability, reward, discount): """ Compute the policy using soft value iteration. """ max_iters = 1000 threshold = 1e-5 V = np.zeros(n_states) for i in range(max_iters): V_prev = V.copy() Q = np.zeros((n_states, n_actions)) for s in range(n_states): for a in range(n_actions): Q[s, a] = np.sum(transition_probability[s, a, :] * (reward + discount * V_prev)) V = np.log(np.sum(np.exp(Q), axis=1)) # Soft value iteration if np.max(np.abs(V - V_prev)) < threshold: break # Compute policy policy = np.zeros((n_states, n_actions)) for s in range(n_states): for a in range(n_actions): Q_sa = np.sum(transition_probability[s, a, :] * (reward + discount * V)) policy[s, a] = np.exp(Q_sa - V[s]) # Subtract V[s] for normalization # Normalize policy policy = policy / np.sum(policy, axis=1, keepdims=True) return policyİnceleme ve Öneriler:
-
Numerik Kararlılık:
-
np.log(np.sum(np.exp(Q), axis=1))ifadesi, özellikle büyükQdeğerlerinde sayısal taşmalara neden olabilir. Log-Sum-Exp tekniği kullanarak bu durumu önleyebilirsiniz.def log_sum_exp(x): max_x = np.max(x, axis=1, keepdims=True) return max_x + np.log(np.sum(np.exp(x - max_x), axis=1, keepdims=True)) # Kullanımı V = log_sum_exp(Q).flatten()
-
-
Politika Hesaplama:
-
Politikanın normalizasyonu yapıldıktan sonra
NaNveyainfdeğerleri oluşabilir. Bunu kontrol etmek için ek önlemler alabilirsiniz.policy = policy / np.sum(policy, axis=1, keepdims=True) policy = np.nan_to_num(policy)
-
-
Performans İyileştirme:
-
Döngüler yerine vektörleştirilmiş işlemler kullanarak performansı artırabilirsiniz.
Q = (transition_probability * (reward[:, np.newaxis] + discount * V_prev)).sum(axis=2) V = log_sum_exp(Q).flatten()
-
6. Genel İyileştirmeler ve Ek Öneriler
-
Hata Kontrolü:
-
Veri setinizin doğru formatta olduğundan emin olun. Örneğin,
State,Action,Next_Statesütunlarının tam olarak bulunduğunu ve sayısal değerler içerdiğini kontrol edin.assert all(col in data.columns for col in ['State', 'Action', 'Next_State']), "CSV dosyasında gerekli sütunlar bulunmuyor."
-
-
Modülerlik:
- Fonksiyonları daha modüler hale getirerek, yeniden kullanımını ve test edilmesini kolaylaştırabilirsiniz.
-
Dokümantasyon ve Yorumlar:
- Fonksiyonlarınızın ve önemli kod bloklarının ne yaptığını açıklayan yorumlar eklemek, kodun bakımını ve anlaşılmasını kolaylaştırır.
-
Logging:
-
Optimizasyon sürecinde ilerlemeyi takip etmek için
printifadeleri veyaloggingmodülü kullanabilirsiniz.import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Örneğin: logger.info(f"Epoch {i}: Gradient norm = {np.linalg.norm(grad)}")
-
-
İptal Koşulları:
- Optimizasyon sürecinde
learning_rateçok büyük veya çok küçükse algoritmanın başarısız olabileceğini göz önünde bulundurarak çeşitli iptal koşulları eklemek faydalı olabilir.
- Optimizasyon sürecinde
-
Test ve Doğrulama:
- Küçük ve bilinen bir ortamda kodunuzu test ederek, beklenen sonuçları verip vermediğini doğrulayın.
7. Sonuç
Kodunuz genel olarak MaxEnt IRL algoritmasının temel bileşenlerini doğru bir şekilde içeriyor. Ancak performans, sayısal kararlılık ve esneklik açısından bazı iyileştirmelere ihtiyaç duyuyor. Yukarıda belirtilen önerileri dikkate alarak kodunuzu daha sağlam, verimli ve bakımı kolay hale getirebilirsiniz. Herhangi bir adımda takıldığınız noktalar veya daha fazla detaylandırma istediğiniz kısımlar olursa, memnuniyetle yardımcı olurum.
-