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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""liberal mind beta
|
3 |
+
|
4 |
+
Automatically generated by Colab.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1WZLrb1Gf63n6vXBvGFEWwIPt1BU_5xc9
|
8 |
+
|
9 |
+
# ***INSTALL LIBRARIES***
|
10 |
+
"""
|
11 |
+
|
12 |
+
pip install stable_baselines3
|
13 |
+
|
14 |
+
pip install datasets
|
15 |
+
|
16 |
+
pip install torch-geometric
|
17 |
+
|
18 |
+
pip install gym==0.21.0
|
19 |
+
|
20 |
+
pip install shimmy
|
21 |
+
|
22 |
+
"""# ***DOWNLOAD DATASETS***"""
|
23 |
+
|
24 |
+
from datasets import load_dataset
|
25 |
+
from huggingface_hub import list_datasets
|
26 |
+
|
27 |
+
def find_and_load_dataset(keyword):
|
28 |
+
# Ищем датасеты по ключевому слову
|
29 |
+
matching_datasets = [ds.id for ds in list_datasets() if keyword.lower() in ds.id.lower()]
|
30 |
+
|
31 |
+
# Проверяем, найдены ли соответствующие датасеты
|
32 |
+
if not matching_datasets:
|
33 |
+
print("Нет датасетов, содержащих указанное ключевое слово.")
|
34 |
+
return None
|
35 |
+
|
36 |
+
# Выбираем первый найденный датасет
|
37 |
+
dataset_name = matching_datasets[0]
|
38 |
+
print(f"Найден датасет: {dataset_name}. Загружаем его...")
|
39 |
+
|
40 |
+
# Загружаем датасет
|
41 |
+
dataset = load_dataset(dataset_name)
|
42 |
+
return dataset
|
43 |
+
|
44 |
+
# Пример использования
|
45 |
+
keyword = input("Введите ключевое слово для поиска датасета: ")
|
46 |
+
dataset = find_and_load_dataset(keyword)
|
47 |
+
|
48 |
+
if dataset:
|
49 |
+
print("Датасет загружен успешно!")
|
50 |
+
print(dataset)
|
51 |
+
|
52 |
+
import os
|
53 |
+
import shutil
|
54 |
+
from datasets import load_dataset
|
55 |
+
|
56 |
+
# Имя и путь для сохранения
|
57 |
+
dataset_name = "Unified-Language-Model-Alignment/Anthropic_HH_Golden" # Замените на точное имя датасета
|
58 |
+
save_dir = "/content/dataset" # Путь для сохранения в директории Google Colab
|
59 |
+
|
60 |
+
# Загружаем датасет
|
61 |
+
dataset = load_dataset(dataset_name)
|
62 |
+
|
63 |
+
# Убеждаемся, что папка для сохранения существует
|
64 |
+
os.makedirs(save_dir, exist_ok=True)
|
65 |
+
|
66 |
+
# Копируем файлы датасета из кэша в нужную директорию
|
67 |
+
for split_cache_files in dataset.cache_files.values():
|
68 |
+
for cache_file in split_cache_files:
|
69 |
+
shutil.copy2(cache_file['filename'], save_dir)
|
70 |
+
|
71 |
+
print(f"Датасет '{dataset_name}' сохранен в папке {save_dir}")
|
72 |
+
|
73 |
+
"""# ***ENCODER TRANSFORMERS MATH AI***"""
|
74 |
+
|
75 |
+
import numpy as np
|
76 |
+
import tensorflow as tf
|
77 |
+
import torch
|
78 |
+
from torch import nn, optim
|
79 |
+
from sklearn.ensemble import RandomForestClassifier
|
80 |
+
from scipy.cluster.hierarchy import linkage, fcluster
|
81 |
+
from sklearn.preprocessing import StandardScaler
|
82 |
+
from stable_baselines3 import PPO
|
83 |
+
|
84 |
+
import numpy as np
|
85 |
+
import torch
|
86 |
+
import torch.nn as nn
|
87 |
+
from stable_baselines3 import PPO
|
88 |
+
from gym import Env
|
89 |
+
from gym.spaces import Discrete, Box
|
90 |
+
|
91 |
+
# Оптимизированные гиперпараметры для многоязыковой LLM
|
92 |
+
ppo_hyperparameters = {
|
93 |
+
"n_steps": 1024, # Увеличение шагов для лучшего захвата зависимости данных
|
94 |
+
"batch_size": 64, # Оптимальный размер для стабилизации обучения
|
95 |
+
"n_epochs": 1, # Баланс скорости обновления и обучения
|
96 |
+
"gamma": 0.99, # Стандартное значение дисконтирования
|
97 |
+
"learning_rate": 3e-4, # Стандартный темп обучения
|
98 |
+
"clip_range": 0.2, # Оптимальное значение для стабильности
|
99 |
+
"gae_lambda": 0.95, # Гладкость обобщенного преимущества
|
100 |
+
"vf_coef": 0.5, # Коэффициент функции ценности
|
101 |
+
"ent_coef": 0.01, # Коэффициент энтропии для исследования
|
102 |
+
"max_grad_norm": 0.5, # Ограничение градиента
|
103 |
+
"target_kl": 0.03, # Целевое значение KL-дивергенции
|
104 |
+
"penalty_coef": 0.05, # Регуляция для устойчивости
|
105 |
+
"epsilon": 0.15, # Умеренная случайность
|
106 |
+
"adv_norm": True, # Нормализация преимущества
|
107 |
+
"weight_init": "xavier" # Инициализация весов
|
108 |
+
}
|
109 |
+
|
110 |
+
|
111 |
+
class ComplexEnv(Env):
|
112 |
+
def __init__(self):
|
113 |
+
super(ComplexEnv, self).__init__()
|
114 |
+
self.action_space = Discrete(3)
|
115 |
+
self.observation_space = Box(low=-10, high=10, shape=(5,), dtype=np.float32)
|
116 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
117 |
+
self.step_count = 0
|
118 |
+
|
119 |
+
def reset(self):
|
120 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
121 |
+
self.step_count = 0
|
122 |
+
return self.state
|
123 |
+
|
124 |
+
def step(self, action):
|
125 |
+
reward = -0.1
|
126 |
+
self.step_count += 1
|
127 |
+
|
128 |
+
if action == 0:
|
129 |
+
reward += 1 if self.state[0] > 0 else -1 * ppo_hyperparameters["penalty_coef"]
|
130 |
+
elif action == 1:
|
131 |
+
reward += 0.5 if np.sum(self.state) > 0 else -2 * ppo_hyperparameters["penalty_coef"]
|
132 |
+
else:
|
133 |
+
reward += -0.5 if self.state[1] < 0 else 1 * ppo_hyperparameters["penalty_coef"]
|
134 |
+
|
135 |
+
self.state += np.random.normal(0, 0.5, size=self.state.shape)
|
136 |
+
|
137 |
+
done = self.step_count >= 100
|
138 |
+
return self.state, reward, done, {}
|
139 |
+
|
140 |
+
# Инициализация среды
|
141 |
+
env = ComplexEnv()
|
142 |
+
|
143 |
+
# Определение и настройка модели PPO с новыми гиперпараметрами и инициализацией весов
|
144 |
+
class EpsilonPPO(PPO):
|
145 |
+
def __init__(self, policy, env, **kwargs):
|
146 |
+
super(EpsilonPPO, self).__init__(policy, env, **kwargs)
|
147 |
+
self.epsilon = ppo_hyperparameters["epsilon"]
|
148 |
+
|
149 |
+
# Инициализация весов
|
150 |
+
for layer in self.policy.modules():
|
151 |
+
if isinstance(layer, (nn.Linear, nn.Conv2d)):
|
152 |
+
if ppo_hyperparameters["weight_init"] == "xavier":
|
153 |
+
nn.init.xavier_uniform_(layer.weight)
|
154 |
+
elif ppo_hyperparameters["weight_init"] == "kaiming":
|
155 |
+
nn.init.kaiming_uniform_(layer.weight)
|
156 |
+
|
157 |
+
def _predict(self, observation, deterministic=False):
|
158 |
+
if np.random.rand() < self.epsilon:
|
159 |
+
return self.env.action_space.sample()
|
160 |
+
else:
|
161 |
+
return super().predict(observation, deterministic=deterministic)
|
162 |
+
|
163 |
+
# Создание PPO модели с новыми гиперпараметрами и нормализацией
|
164 |
+
model = EpsilonPPO(
|
165 |
+
policy="MlpPolicy",
|
166 |
+
env=env,
|
167 |
+
verbose=1,
|
168 |
+
n_steps=ppo_hyperparameters["n_steps"],
|
169 |
+
batch_size=ppo_hyperparameters["batch_size"],
|
170 |
+
n_epochs=ppo_hyperparameters["n_epochs"],
|
171 |
+
gamma=ppo_hyperparameters["gamma"],
|
172 |
+
learning_rate=ppo_hyperparameters["learning_rate"],
|
173 |
+
clip_range=ppo_hyperparameters["clip_range"],
|
174 |
+
gae_lambda=ppo_hyperparameters["gae_lambda"],
|
175 |
+
vf_coef=ppo_hyperparameters["vf_coef"],
|
176 |
+
ent_coef=ppo_hyperparameters["ent_coef"],
|
177 |
+
max_grad_norm=ppo_hyperparameters["max_grad_norm"],
|
178 |
+
target_kl=ppo_hyperparameters["target_kl"]
|
179 |
+
)
|
180 |
+
|
181 |
+
# Обучение модели
|
182 |
+
model.learn(total_timesteps=50000)
|
183 |
+
|
184 |
+
# Проверка работы агента
|
185 |
+
obs = env.reset()
|
186 |
+
for _ in range(100):
|
187 |
+
action, _ = model.predict(obs)
|
188 |
+
obs, reward, done, _ = env.step(action)
|
189 |
+
if done:
|
190 |
+
obs = env.reset()
|
191 |
+
|
192 |
+
import numpy as np
|
193 |
+
import torch
|
194 |
+
import torch.nn as nn
|
195 |
+
from sklearn.ensemble import RandomForestClassifier
|
196 |
+
from sklearn.cluster import AgglomerativeClustering
|
197 |
+
from scipy.spatial.distance import euclidean
|
198 |
+
from sklearn.preprocessing import StandardScaler
|
199 |
+
from stable_baselines3 import PPO
|
200 |
+
from gym import Env
|
201 |
+
from gym.spaces import Discrete, Box
|
202 |
+
|
203 |
+
# Настройка Random Forest
|
204 |
+
def classify_data(X, y):
|
205 |
+
rf = RandomForestClassifier(n_estimators=100)
|
206 |
+
rf.fit(X, y)
|
207 |
+
feature_importances = rf.feature_importances_
|
208 |
+
return feature_importances, rf
|
209 |
+
|
210 |
+
# Иерархическая кластеризация
|
211 |
+
def cluster_data(X):
|
212 |
+
clustering = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')
|
213 |
+
clusters = clustering.fit_predict(X)
|
214 |
+
return clusters
|
215 |
+
|
216 |
+
class LSTMModel(nn.Module):
|
217 |
+
def __init__(self, input_size, hidden_size, output_size):
|
218 |
+
super(LSTMModel, self).__init__()
|
219 |
+
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
|
220 |
+
self.fc = nn.Linear(hidden_size, output_size)
|
221 |
+
|
222 |
+
def forward(self, x):
|
223 |
+
_, (hn, _) = self.lstm(x) # передаём через LSTM
|
224 |
+
out = self.fc(hn[-1]) # последний скрытый слой
|
225 |
+
return out
|
226 |
+
|
227 |
+
# Параметры LSTM
|
228 |
+
input_size = 5
|
229 |
+
hidden_size = 32
|
230 |
+
output_size = 3
|
231 |
+
lstm_agent = LSTMModel(input_size, hidden_size, output_size)
|
232 |
+
|
233 |
+
class ComplexEnvWithLSTM(Env):
|
234 |
+
def __init__(self):
|
235 |
+
super(ComplexEnvWithLSTM, self).__init__()
|
236 |
+
self.action_space = Discrete(3)
|
237 |
+
self.observation_space = Box(low=-10, high=10, shape=(5,), dtype=np.float32)
|
238 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
239 |
+
self.step_count = 0
|
240 |
+
|
241 |
+
def reset(self):
|
242 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
243 |
+
self.step_count = 0
|
244 |
+
return self.state
|
245 |
+
|
246 |
+
def step(self, action):
|
247 |
+
reward = -0.1
|
248 |
+
self.step_count += 1
|
249 |
+
|
250 |
+
# Логика наград
|
251 |
+
if action == 0:
|
252 |
+
reward += 1 if self.state[0] > 0 else -0.5
|
253 |
+
elif action == 1:
|
254 |
+
reward += 0.5 if np.sum(self.state) > 0 else -1
|
255 |
+
else:
|
256 |
+
reward += -0.5 if self.state[1] < 0 else 1
|
257 |
+
|
258 |
+
# Обновляем состояние с учетом LSTM
|
259 |
+
self.state += np.random.normal(0, 0.5, size=self.state.shape)
|
260 |
+
|
261 |
+
done = self.step_count >= 100
|
262 |
+
return self.state, reward, done, {}
|
263 |
+
|
264 |
+
env = ComplexEnvWithLSTM()
|
265 |
+
|
266 |
+
def classify_data(X, y):
|
267 |
+
rf = RandomForestClassifier(n_estimators=100)
|
268 |
+
rf.fit(X, y)
|
269 |
+
feature_importances = rf.feature_importances_
|
270 |
+
return feature_importances, rf
|
271 |
+
|
272 |
+
def cluster_data(X):
|
273 |
+
clustering = AgglomerativeClustering(n_clusters=5, metric='euclidean', linkage='ward')
|
274 |
+
clusters = clustering.fit_predict(X)
|
275 |
+
return clusters
|
276 |
+
class AdvancedLSTMModel(nn.Module):
|
277 |
+
def __init__(self, input_size, hidden_size, output_size, num_layers=2, dropout=0.3, use_sigmoid=True):
|
278 |
+
super(AdvancedLSTMModel, self).__init__()
|
279 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
280 |
+
|
281 |
+
# Полносвязные слои
|
282 |
+
self.fc1 = nn.Linear(hidden_size, 1000)
|
283 |
+
self.fc2 = nn.Linear(1000, 2000)
|
284 |
+
self.activation = nn.Sigmoid() if use_sigmoid else nn.ReLU()
|
285 |
+
|
286 |
+
def forward(self, x):
|
287 |
+
_, (hn, _) = self.lstm(x)
|
288 |
+
x = self.fc1(hn[-1])
|
289 |
+
x = self.activation(x)
|
290 |
+
x = self.fc2(x)
|
291 |
+
return x
|
292 |
+
|
293 |
+
# Параметры LSTM
|
294 |
+
input_size = 5
|
295 |
+
hidden_size = 256
|
296 |
+
output_size = 2000
|
297 |
+
num_layers = 3
|
298 |
+
dropout = 0.3
|
299 |
+
use_sigmoid = True
|
300 |
+
lstm_agent = AdvancedLSTMModel(input_size, hidden_size, output_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
301 |
+
class ComplexEnvWithLSTM(Env):
|
302 |
+
def __init__(self):
|
303 |
+
super(ComplexEnvWithLSTM, self).__init__()
|
304 |
+
self.action_space = Discrete(3)
|
305 |
+
self.observation_space = Box(low=-10, high=10, shape=(5,), dtype=np.float32)
|
306 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
307 |
+
self.step_count = 0
|
308 |
+
|
309 |
+
def reset(self):
|
310 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
311 |
+
self.step_count = 0
|
312 |
+
return self.state
|
313 |
+
|
314 |
+
def step(self, action):
|
315 |
+
reward = -0.1
|
316 |
+
self.step_count += 1
|
317 |
+
|
318 |
+
if action == 0:
|
319 |
+
reward += 1 if self.state[0] > 0 else -0.5
|
320 |
+
elif action == 1:
|
321 |
+
reward += 0.5 if np.sum(self.state) > 0 else -1
|
322 |
+
else:
|
323 |
+
reward += -0.5 if self.state[1] < 0 else 1
|
324 |
+
|
325 |
+
# Обновляем состояние
|
326 |
+
self.state += np.random.normal(0, 0.5, size=self.state.shape)
|
327 |
+
|
328 |
+
done = self.step_count >= 100
|
329 |
+
return self.state, reward, done, {}
|
330 |
+
|
331 |
+
env = ComplexEnvWithLSTM()
|
332 |
+
|
333 |
+
# Генерация данных для Random Forest и кластеризации
|
334 |
+
X = np.random.rand(100, 5) # Замените на реальные данные
|
335 |
+
y = np.random.randint(0, 2, size=100)
|
336 |
+
feature_importances, rf = classify_data(X, y)
|
337 |
+
clusters = cluster_data(X)
|
338 |
+
|
339 |
+
# Настройка PPO с LSTM
|
340 |
+
model = PPO(
|
341 |
+
policy="MlpPolicy",
|
342 |
+
env=env,
|
343 |
+
verbose=1,
|
344 |
+
learning_rate=5e-4,
|
345 |
+
n_steps=512,
|
346 |
+
batch_size=32,
|
347 |
+
n_epochs=4,
|
348 |
+
gamma=0.99,
|
349 |
+
clip_range=0.2,
|
350 |
+
gae_lambda=0.95,
|
351 |
+
vf_coef=0.5,
|
352 |
+
ent_coef=0.005,
|
353 |
+
max_grad_norm=0.5,
|
354 |
+
target_kl=0.03,
|
355 |
+
)
|
356 |
+
|
357 |
+
# Обучение PPO с использованием LSTM
|
358 |
+
model.learn(total_timesteps=20000)
|
359 |
+
|
360 |
+
# Проверка работы агента
|
361 |
+
obs = env.reset()
|
362 |
+
obs = torch.tensor(obs, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
|
363 |
+
for _ in range(100):
|
364 |
+
action_probs = lstm_agent(obs)
|
365 |
+
action = action_probs.argmax().item()
|
366 |
+
obs, reward, done, _ = env.step(action)
|
367 |
+
obs = torch.tensor(obs, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
|
368 |
+
if done:
|
369 |
+
obs = env.reset()
|
370 |
+
|
371 |
+
"""# ***DECODER TRANSFORMERS MATH AI***"""
|
372 |
+
|
373 |
+
import numpy as np
|
374 |
+
import torch
|
375 |
+
import torch.nn as nn
|
376 |
+
import torch.optim as optim
|
377 |
+
from sklearn.linear_model import LinearRegression
|
378 |
+
from stable_baselines3 import PPO
|
379 |
+
from gym import Env
|
380 |
+
from gym.spaces import Discrete, Box
|
381 |
+
|
382 |
+
# Функция множественной линейной регрессии
|
383 |
+
def distribute_outputs(X, y):
|
384 |
+
lin_reg = LinearRegression()
|
385 |
+
lin_reg.fit(X, y)
|
386 |
+
distributed_outputs = lin_reg.predict(X)
|
387 |
+
return distributed_outputs
|
388 |
+
|
389 |
+
class LSTMDecoderModel(nn.Module):
|
390 |
+
def __init__(self, input_size, hidden_size, output_size, num_layers=2, dropout=0.3, use_sigmoid=True):
|
391 |
+
super(LSTMDecoderModel, self).__init__()
|
392 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
393 |
+
|
394 |
+
# Полносвязные слои
|
395 |
+
self.fc1 = nn.Linear(hidden_size, 1000)
|
396 |
+
self.fc2 = nn.Linear(1000, 2000)
|
397 |
+
self.activation = nn.Sigmoid() if use_sigmoid else nn.ReLU()
|
398 |
+
|
399 |
+
def forward(self, x):
|
400 |
+
_, (hn, _) = self.lstm(x)
|
401 |
+
x = self.fc1(hn[-1])
|
402 |
+
x = self.activation(x)
|
403 |
+
x = self.fc2(x)
|
404 |
+
return x
|
405 |
+
|
406 |
+
# Параметры модели
|
407 |
+
input_size = 5
|
408 |
+
hidden_size = 256
|
409 |
+
output_size = 2000
|
410 |
+
num_layers = 3
|
411 |
+
dropout = 0.3
|
412 |
+
use_sigmoid = True
|
413 |
+
lstm_decoder = LSTMDecoderModel(input_size, hidden_size, output_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
414 |
+
|
415 |
+
class ComplexEnvForDecoder(Env):
|
416 |
+
def __init__(self):
|
417 |
+
super(ComplexEnvForDecoder, self).__init__()
|
418 |
+
self.action_space = Discrete(3)
|
419 |
+
self.observation_space = Box(low=-10, high=10, shape=(5,), dtype=np.float32)
|
420 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
421 |
+
self.step_count = 0
|
422 |
+
|
423 |
+
def reset(self):
|
424 |
+
self.state = np.random.uniform(low=-1, high=1, size=(5,))
|
425 |
+
self.step_count = 0
|
426 |
+
return self.state
|
427 |
+
|
428 |
+
def step(self, action):
|
429 |
+
reward = -0.1
|
430 |
+
self.step_count += 1
|
431 |
+
|
432 |
+
if action == 0:
|
433 |
+
reward += 1 if self.state[0] > 0 else -0.5
|
434 |
+
elif action == 1:
|
435 |
+
reward += 0.5 if np.sum(self.state) > 0 else -1
|
436 |
+
else:
|
437 |
+
reward += -0.5 if self.state[1] < 0 else 1
|
438 |
+
|
439 |
+
self.state += np.random.normal(0, 0.5, size=self.state.shape)
|
440 |
+
done = self.step_count >= 100
|
441 |
+
return self.state, reward, done, {}
|
442 |
+
|
443 |
+
env_decoder = ComplexEnvForDecoder()
|
444 |
+
|
445 |
+
# Генерация данных
|
446 |
+
X = np.random.rand(100, 5) # Замените на реальные данные
|
447 |
+
y = np.random.randint(0, 2, size=100)
|
448 |
+
distributed_outputs = distribute_outputs(X, y)
|
449 |
+
|
450 |
+
# Настройка PPO с LSTM-декодером
|
451 |
+
model_decoder = PPO(
|
452 |
+
policy="MlpPolicy",
|
453 |
+
env=env_decoder,
|
454 |
+
verbose=1,
|
455 |
+
learning_rate=5e-4,
|
456 |
+
n_steps=512,
|
457 |
+
batch_size=32,
|
458 |
+
n_epochs=4,
|
459 |
+
gamma=0.99,
|
460 |
+
clip_range=0.2,
|
461 |
+
gae_lambda=0.95,
|
462 |
+
vf_coef=0.5,
|
463 |
+
ent_coef=0.005,
|
464 |
+
max_grad_norm=0.5,
|
465 |
+
target_kl=0.03,
|
466 |
+
)
|
467 |
+
|
468 |
+
# Обучение PPO с использованием LSTM-декодера
|
469 |
+
model_decoder.learn(total_timesteps=20000)
|
470 |
+
|
471 |
+
# Проверка работы декодера
|
472 |
+
obs = env_decoder.reset()
|
473 |
+
obs = torch.tensor(obs, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
|
474 |
+
for _ in range(100):
|
475 |
+
action_probs = lstm_decoder(obs)
|
476 |
+
action = action_probs.argmax().item()
|
477 |
+
obs, reward, done, _ = env_decoder.step(action)
|
478 |
+
obs = torch.tensor(obs, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
|
479 |
+
if done:
|
480 |
+
obs = env_decoder.reset()
|
481 |
+
|
482 |
+
"""# ***TRANSFORMERS MATH AI***"""
|
483 |
+
|
484 |
+
import numpy as np
|
485 |
+
import torch
|
486 |
+
import torch.nn as nn
|
487 |
+
import torch.optim as optim
|
488 |
+
from sklearn.ensemble import RandomForestClassifier
|
489 |
+
from sklearn.cluster import AgglomerativeClustering
|
490 |
+
from sklearn.linear_model import LinearRegression
|
491 |
+
from stable_baselines3 import PPO
|
492 |
+
from gym import Env
|
493 |
+
from gym.spaces import Discrete, Box
|
494 |
+
|
495 |
+
class EncoderLSTMModel(nn.Module):
|
496 |
+
def __init__(self, input_size, hidden_size, output_size, num_layers=2, dropout=0.3, use_sigmoid=True):
|
497 |
+
super(EncoderLSTMModel, self).__init__()
|
498 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
499 |
+
self.fc1 = nn.Linear(hidden_size, output_size)
|
500 |
+
self.activation = nn.Sigmoid() if use_sigmoid else nn.ReLU()
|
501 |
+
|
502 |
+
def forward(self, x):
|
503 |
+
_, (hn, _) = self.lstm(x)
|
504 |
+
x = self.fc1(hn[-1])
|
505 |
+
return self.activation(x)
|
506 |
+
|
507 |
+
class DecoderLSTMModel(nn.Module):
|
508 |
+
def __init__(self, input_size, hidden_size, output_size, num_layers=2, dropout=0.3, use_sigmoid=True):
|
509 |
+
super(DecoderLSTMModel, self).__init__()
|
510 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
511 |
+
self.fc1 = nn.Linear(hidden_size, output_size)
|
512 |
+
self.activation = nn.Sigmoid() if use_sigmoid else nn.ReLU()
|
513 |
+
|
514 |
+
def forward(self, x):
|
515 |
+
_, (hn, _) = self.lstm(x)
|
516 |
+
x = self.fc1(hn[-1])
|
517 |
+
return self.activation(x)
|
518 |
+
|
519 |
+
class TransformerModule(nn.Module):
|
520 |
+
def __init__(self, input_size, hidden_size, num_heads=2, num_layers=2):
|
521 |
+
super(TransformerModule, self).__init__()
|
522 |
+
self.transformer_layer = nn.Transformer(d_model=input_size, nhead=num_heads, num_encoder_layers=num_layers, num_decoder_layers=num_layers)
|
523 |
+
self.fc = nn.Linear(input_size, hidden_size)
|
524 |
+
|
525 |
+
def forward(self, src, tgt):
|
526 |
+
# Проходим через трансформер
|
527 |
+
output = self.transformer_layer(src, tgt)
|
528 |
+
# Преобразуем выход трансформера для передачи в декодер
|
529 |
+
return self.fc(output)
|
530 |
+
|
531 |
+
# Параметры для модели
|
532 |
+
input_size = 32 # Сделаем input_size кратным num_heads
|
533 |
+
hidden_size = 256
|
534 |
+
output_size = 2000
|
535 |
+
num_heads = 4 # Убедимся, что input_size % num_heads == 0
|
536 |
+
num_layers = 2
|
537 |
+
dropout = 0.3
|
538 |
+
use_sigmoid = True
|
539 |
+
|
540 |
+
# Инициализация компонентов
|
541 |
+
encoder = EncoderLSTMModel(input_size, hidden_size, output_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
542 |
+
decoder = DecoderLSTMModel(input_size, hidden_size, output_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
543 |
+
transformer = TransformerModule(input_size, hidden_size, num_heads=num_heads, num_layers=num_layers)
|
544 |
+
|
545 |
+
import torch
|
546 |
+
import torch.nn as nn
|
547 |
+
|
548 |
+
# Энкодер на основе LSTM
|
549 |
+
class EncoderLSTMModel(nn.Module):
|
550 |
+
def __init__(self, input_size, hidden_size, num_layers=1, dropout=0.0, use_sigmoid=False):
|
551 |
+
super(EncoderLSTMModel, self).__init__()
|
552 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
553 |
+
self.fc = nn.Linear(hidden_size, input_size) # Сохраняем выходной размер равным input_size
|
554 |
+
self.use_sigmoid = use_sigmoid
|
555 |
+
|
556 |
+
def forward(self, x):
|
557 |
+
lstm_out, _ = self.lstm(x)
|
558 |
+
output = self.fc(lstm_out[:, -1, :]) # Используем только последний выход LSTM
|
559 |
+
if self.use_sigmoid:
|
560 |
+
output = torch.sigmoid(output)
|
561 |
+
return output
|
562 |
+
|
563 |
+
# Декодер на основе LSTM
|
564 |
+
class DecoderLSTMModel(nn.Module):
|
565 |
+
def __init__(self, input_size, hidden_size, num_layers=1, dropout=0.0, use_sigmoid=False):
|
566 |
+
super(DecoderLSTMModel, self).__init__()
|
567 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=num_layers, dropout=dropout, batch_first=True)
|
568 |
+
self.fc = nn.Linear(hidden_size, input_size) # Сохраняем выходной размер равным input_size
|
569 |
+
self.use_sigmoid = use_sigmoid
|
570 |
+
|
571 |
+
def forward(self, x):
|
572 |
+
lstm_out, _ = self.lstm(x)
|
573 |
+
output = self.fc(lstm_out[:, -1, :]) # Используем только последний выход LSTM
|
574 |
+
if self.use_sigmoid:
|
575 |
+
output = torch.sigmoid(output)
|
576 |
+
return output
|
577 |
+
|
578 |
+
# Трансформер
|
579 |
+
class TransformerModule(nn.Module):
|
580 |
+
def __init__(self, input_size, num_heads=4, num_layers=2):
|
581 |
+
super(TransformerModule, self).__init__()
|
582 |
+
self.transformer_layer = nn.Transformer(
|
583 |
+
d_model=input_size, # Убедитесь, что это соответствует размерности входа
|
584 |
+
nhead=num_heads,
|
585 |
+
num_encoder_layers=num_layers,
|
586 |
+
num_decoder_layers=num_layers
|
587 |
+
)
|
588 |
+
self.fc = nn.Linear(input_size, input_size) # Для преобразования выходных данных
|
589 |
+
|
590 |
+
def forward(self, src, tgt):
|
591 |
+
# Проверка размерности входных данных
|
592 |
+
print(f"src shape before transformer: {src.shape}")
|
593 |
+
print(f"tgt shape before transformer: {tgt.shape}")
|
594 |
+
|
595 |
+
# Проходим через трансформер
|
596 |
+
output = self.transformer_layer(src, tgt)
|
597 |
+
|
598 |
+
# Преобразуем выход трансформера для передачи в декодер
|
599 |
+
return self.fc(output)
|
600 |
+
|
601 |
+
# Объединённая модель
|
602 |
+
class CombinedModel(nn.Module):
|
603 |
+
def __init__(self, encoder, decoder, transformer):
|
604 |
+
super(CombinedModel, self).__init__()
|
605 |
+
self.encoder = encoder
|
606 |
+
self.decoder = decoder
|
607 |
+
self.transformer = transformer
|
608 |
+
|
609 |
+
def forward(self, x):
|
610 |
+
# Пропускаем через энкодер
|
611 |
+
encoded = self.encoder(x)
|
612 |
+
|
613 |
+
# Подготавливаем входы и выходы для трансформера
|
614 |
+
src = encoded.unsqueeze(1) # Изменяем размерность: (batch_size, 1, input_size)
|
615 |
+
tgt = torch.zeros_like(src) # Создаём нулевую целевую последовательность
|
616 |
+
|
617 |
+
# Убедимся, что размеры правильные
|
618 |
+
print(f"CombinedModel: src shape: {src.shape}, tgt shape: {tgt.shape}")
|
619 |
+
|
620 |
+
# Пропускаем через трансформер
|
621 |
+
transformed = self.transformer(src, tgt)
|
622 |
+
|
623 |
+
# Передаём в декодер
|
624 |
+
output = self.decoder(transformed)
|
625 |
+
return output
|
626 |
+
|
627 |
+
# Параметры для модели
|
628 |
+
input_size = 32 # Размерность входа
|
629 |
+
hidden_size = 256 # Размерность скрытого слоя
|
630 |
+
num_heads = 4 # Количество голов
|
631 |
+
num_layers = 2 # Количество слоёв
|
632 |
+
dropout = 0.3 # Дропаут
|
633 |
+
use_sigmoid = True # Использование сигмоиды
|
634 |
+
|
635 |
+
# Инициализация компонентов
|
636 |
+
encoder = EncoderLSTMModel(input_size, hidden_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
637 |
+
decoder = DecoderLSTMModel(input_size, hidden_size, num_layers=num_layers, dropout=dropout, use_sigmoid=use_sigmoid)
|
638 |
+
transformer = TransformerModule(input_size, num_heads=num_heads, num_layers=num_layers)
|
639 |
+
|
640 |
+
# Создание объединённой модели
|
641 |
+
combined_model = CombinedModel(encoder, decoder, transformer)
|
642 |
+
|
643 |
+
# Пример данных
|
644 |
+
batch_size = 10
|
645 |
+
seq_length = 5
|
646 |
+
example_input = torch.randn((batch_size, seq_length, input_size)) # Генерация случайного входа
|
647 |
+
output = combined_model(example_input)
|
648 |
+
|
649 |
+
print("Output shape:", output.shape) # Вывод формы результата
|
650 |
+
|
651 |
+
"""# ***CREATION AI***"""
|
652 |
+
|
653 |
+
import torch
|
654 |
+
import torch.nn as nn
|
655 |
+
import torch.optim as optim
|
656 |
+
import numpy as np
|
657 |
+
from tqdm import tqdm
|
658 |
+
|
659 |
+
# Параметры диффузии и обучения
|
660 |
+
num_steps = 1000 # Количество шагов диффузии
|
661 |
+
input_dim = 784 # Например, для изобр��жений 28x28 = 784
|
662 |
+
batch_size = 64 # Размер батча
|
663 |
+
learning_rate = 1e-4
|
664 |
+
|
665 |
+
# Параметры альфа
|
666 |
+
beta_start = 1e-4
|
667 |
+
beta_end = 0.02
|
668 |
+
beta = np.linspace(beta_start, beta_end, num_steps)
|
669 |
+
alpha = 1 - beta
|
670 |
+
alpha_cumprod = np.cumprod(alpha)
|
671 |
+
|
672 |
+
# Гиперпараметры модели
|
673 |
+
class DiffusionModel(nn.Module):
|
674 |
+
def init(
|
675 |
+
self, input_dim, hidden_dim=512, output_dim=784,
|
676 |
+
num_layers=3, activation_function="ReLU", batch_norm=False, layer_norm=False,
|
677 |
+
use_skip_connections=True, dropout_rate=0.1, use_time_embedding=True,
|
678 |
+
time_embedding_dim=16, noise_scaling_factor=0.1, optimizer="adam",
|
679 |
+
learning_rate=1e-4, weight_decay=1e-5, gradient_clip_value=5.0,
|
680 |
+
scheduler_step_size=50, scheduler_gamma=0.95, beta_schedule="linear",
|
681 |
+
noise_type="gaussian", noise_seed=None, min_noise_std=0.1, max_noise_std=1.0,
|
682 |
+
use_positional_encoding=False, positional_encoding_scale=1.0,
|
683 |
+
max_training_epochs=100, min_learning_rate=1e-6, warmup_steps=500
|
684 |
+
):
|
685 |
+
super(DiffusionModel, self).init()
|
686 |
+
|
687 |
+
# Основные гиперпараметры
|
688 |
+
self.use_skip_connections = use_skip_connections
|
689 |
+
self.use_time_embedding = use_time_embedding
|
690 |
+
self.noise_scaling_factor = noise_scaling_factor
|
691 |
+
self.time_embedding_dim = time_embedding_dim
|
692 |
+
self.noise_type = noise_type
|
693 |
+
self.min_noise_std = min_noise_std
|
694 |
+
self.max_noise_std = max_noise_std
|
695 |
+
self.noise_seed = noise_seed
|
696 |
+
self.use_positional_encoding = use_positional_encoding
|
697 |
+
self.positional_encoding_scale = positional_encoding_scale
|
698 |
+
|
699 |
+
# Инициализация архитектуры сети
|
700 |
+
layers = []
|
701 |
+
in_dim = input_dim + (self.time_embedding_dim if use_time_embedding else 0)
|
702 |
+
|
703 |
+
for _ in range(num_layers):
|
704 |
+
layers.append(nn.Linear(in_dim, hidden_dim))
|
705 |
+
|
706 |
+
if batch_norm:
|
707 |
+
layers.append(nn.BatchNorm1d(hidden_dim))
|
708 |
+
elif layer_norm:
|
709 |
+
layers.append(nn.LayerNorm(hidden_dim))
|
710 |
+
|
711 |
+
if activation_function.lower() == "relu":
|
712 |
+
layers.append(nn.ReLU())
|
713 |
+
elif activation_function.lower() == "leakyrelu":
|
714 |
+
layers.append(nn.LeakyReLU())
|
715 |
+
elif activation_function.lower() == "tanh":
|
716 |
+
layers.append(nn.Tanh())
|
717 |
+
|
718 |
+
if dropout_rate > 0:
|
719 |
+
layers.append(nn.Dropout(dropout_rate))
|
720 |
+
|
721 |
+
in_dim = hidden_dim
|
722 |
+
|
723 |
+
layers.append(nn.Linear(hidden_dim, output_dim))
|
724 |
+
self.network = nn.Sequential(*layers)
|
725 |
+
|
726 |
+
def forward(self, x, t):
|
727 |
+
if self.use_time_embedding:
|
728 |
+
t_embedding = torch.sin(t.float() * 2 * np.pi / num_steps).unsqueeze(-1)
|
729 |
+
t_embedding = t_embedding * self.time_embedding_dim
|
730 |
+
x = torch.cat([x, t_embedding], dim=1)
|
731 |
+
|
732 |
+
return self.network(x)
|
733 |
+
|
734 |
+
|
735 |
+
# Функция добавления шума
|
736 |
+
def add_noise(x, t, noise_type="gaussian", min_noise_std=0.1, max_noise_std=1.0,
|
737 |
+
noise_seed=None, noise_scaling_factor=0.1, beta_schedule="linear"):
|
738 |
+
|
739 |
+
if noise_seed is not None:
|
740 |
+
torch.manual_seed(noise_seed)
|
741 |
+
|
742 |
+
noise_std = min_noise_std + t * (max_noise_std - min_noise_std) / num_steps
|
743 |
+
noise = torch.randn_like(x) * noise_std if noise_type == "gaussian" else torch.rand_like(x) * noise_std
|
744 |
+
|
745 |
+
if beta_schedule == "linear":
|
746 |
+
alpha_t = alpha_cumprod[t].view(-1, 1)
|
747 |
+
elif beta_schedule == "cosine":
|
748 |
+
alpha_t = torch.cos(t * np.pi / num_steps).view(-1, 1)
|
749 |
+
|
750 |
+
noisy_x = torch.sqrt(alpha_t) * x + torch.sqrt(1 - alpha_t) * noise * noise_scaling_factor
|
751 |
+
return noisy_x
|
752 |
+
|
753 |
+
"""# ***DIFFUSION TRANSFORMERS***"""
|
754 |
+
|
755 |
+
import torch
|
756 |
+
import torch.nn as nn
|
757 |
+
import torch.optim as optim
|
758 |
+
import numpy as np
|
759 |
+
from tqdm import tqdm
|
760 |
+
|
761 |
+
# Параметры
|
762 |
+
num_steps = 1000 # Количество шагов диффузии
|
763 |
+
input_dim = 784 # Например, для изображений 28x28 = 784
|
764 |
+
batch_size = 64 # Размер батча
|
765 |
+
learning_rate = 1e-4
|
766 |
+
|
767 |
+
# Параметры альфа
|
768 |
+
beta_start = 1e-4
|
769 |
+
beta_end = 0.02
|
770 |
+
beta = np.linspace(beta_start, beta_end, num_steps)
|
771 |
+
alpha = 1 - beta
|
772 |
+
alpha_cumprod = np.cumprod(alpha)
|
773 |
+
|
774 |
+
# Преобразование alpha_cumprod в тензор PyTorch
|
775 |
+
alpha_cumprod_tensor = torch.tensor(alpha_cumprod, dtype=torch.float32)
|
776 |
+
|
777 |
+
# Определение диффузионного энкодера
|
778 |
+
class DiffusionEncoder(nn.Module):
|
779 |
+
def __init__(self):
|
780 |
+
super(DiffusionEncoder, self).__init__()
|
781 |
+
self.network = nn.Sequential(
|
782 |
+
nn.Linear(input_dim + 1, 512), # Добавляем 1 для временной переменной
|
783 |
+
nn.ReLU(),
|
784 |
+
nn.Linear(512, 512),
|
785 |
+
nn.ReLU(),
|
786 |
+
nn.Linear(512, input_dim) # Выходной размер должен соответствовать input_dim
|
787 |
+
)
|
788 |
+
|
789 |
+
def forward(self, x, t):
|
790 |
+
t_embedding = torch.sin(t.float() * 2 * np.pi / num_steps).unsqueeze(-1) # Временная переменная
|
791 |
+
x = torch.cat([x, t_embedding], dim=1) # Объединяем x и t_embedding
|
792 |
+
return self.network(x)
|
793 |
+
|
794 |
+
# Определение декодера (полносвязная нейросеть)
|
795 |
+
class FullyConnectedDecoder(nn.Module):
|
796 |
+
def __init__(self):
|
797 |
+
super(FullyConnectedDecoder, self).__init__()
|
798 |
+
self.network = nn.Sequential(
|
799 |
+
nn.Linear(input_dim, 512),
|
800 |
+
nn.ReLU(),
|
801 |
+
nn.Linear(512, 512),
|
802 |
+
nn.ReLU(),
|
803 |
+
nn.Linear(512, input_dim)
|
804 |
+
)
|
805 |
+
|
806 |
+
def forward(self, x):
|
807 |
+
return self.network(x)
|
808 |
+
|
809 |
+
# Функция добавления шума
|
810 |
+
def add_noise(x, t):
|
811 |
+
noise = torch.randn_like(x)
|
812 |
+
alpha_t = alpha_cumprod_tensor[t].view(-1, 1) # Индексация тензора alpha_cumprod_tensor
|
813 |
+
noisy_x = torch.sqrt(alpha_t) * x + torch.sqrt(1 - alpha_t) * noise
|
814 |
+
return noisy_x, noise
|
815 |
+
|
816 |
+
# Инициализация модели и оптимизатора
|
817 |
+
encoder = DiffusionEncoder()
|
818 |
+
decoder = FullyConnectedDecoder()
|
819 |
+
optimizer = optim.Adam(list(encoder.parameters()) + list(decoder.parameters()), lr=learning_rate)
|
820 |
+
|
821 |
+
# Обучение модели
|
822 |
+
for epoch in range(2): # 100 эпох
|
823 |
+
for _ in tqdm(range(1000)): # 1000 шагов обучения
|
824 |
+
# Генерация случайных данных
|
825 |
+
x = torch.randn(batch_size, input_dim)
|
826 |
+
t = torch.randint(0, num_steps, (batch_size,)) # Случайные временные шаги
|
827 |
+
|
828 |
+
# Добавление шума
|
829 |
+
noisy_x, noise = add_noise(x, t)
|
830 |
+
|
831 |
+
# Прямой проход через энкодер
|
832 |
+
encoded = encoder(noisy_x, t)
|
833 |
+
|
834 |
+
# Прямой проход через декодер
|
835 |
+
decoded = decoder(encoded)
|
836 |
+
|
837 |
+
# Расчет потерь (например, MSE)
|
838 |
+
loss = nn.MSELoss()(decoded, x)
|
839 |
+
|
840 |
+
# Обратный проход и обновление весов
|
841 |
+
optimizer.zero_grad()
|
842 |
+
loss.backward()
|
843 |
+
optimizer.step()
|
844 |
+
|
845 |
+
print(f'Epoch {epoch + 1}, Loss: {loss.item():.4f}')
|
846 |
+
|
847 |
+
"""# ***SELF-AWARNESS AI***"""
|
848 |
+
|
849 |
+
import torch
|
850 |
+
import torch.nn as nn
|
851 |
+
import torch.optim as optim
|
852 |
+
import torch.nn.functional as F
|
853 |
+
from tqdm import tqdm
|
854 |
+
|
855 |
+
# Гиперпараметры
|
856 |
+
input_size = 10 # Размерность входных данных
|
857 |
+
hidden_size = 20 # Размер скрытого слоя LSTM
|
858 |
+
num_layers = 2 # Количество слоев LSTM
|
859 |
+
seq_len = 5 # Длина последовательности
|
860 |
+
batch_size = 1 # Размер батча
|
861 |
+
num_epochs = 5 # Количество эпох
|
862 |
+
learning_rate = 1e-4 # Скорость обучения
|
863 |
+
|
864 |
+
# Гиперпараметры для графовой нейросети
|
865 |
+
gnn_params = {
|
866 |
+
'input_dim': input_size, # Входной размер
|
867 |
+
'hidden_dim': 32, # Скрытый размер первого слоя
|
868 |
+
'hidden_dim_2': 64, # Скрытый размер второго слоя
|
869 |
+
'output_dim': input_size, # Выходной размер
|
870 |
+
'activation_function': 'ReLU', # Функция активации
|
871 |
+
'dropout_rate': 0.2, # Дроп-аут
|
872 |
+
'batch_norm': True, # Использовать батч-нормализацию
|
873 |
+
}
|
874 |
+
|
875 |
+
# Гиперпараметры для LSTM
|
876 |
+
lstm_params = {
|
877 |
+
'input_size': input_size, # Размерность входа
|
878 |
+
'hidden_size': hidden_size, # Размер скрытого слоя
|
879 |
+
'num_layers': num_layers, # Количество слоев
|
880 |
+
'dropout': 0.2, # Дроп-аут
|
881 |
+
'bidirectional': False, # Двунаправленный LSTM
|
882 |
+
'activation_function': 'Tanh', # Функция активации
|
883 |
+
}
|
884 |
+
|
885 |
+
# Определение графовой нейросети
|
886 |
+
class GraphNeuralNetwork(nn.Module):
|
887 |
+
def __init__(self, params):
|
888 |
+
super(GraphNeuralNetwork, self).__init__()
|
889 |
+
self.fc1 = nn.Linear(params['input_dim'], params['hidden_dim'])
|
890 |
+
self.fc2 = nn.Linear(params['hidden_dim'], params['hidden_dim_2'])
|
891 |
+
self.fc3 = nn.Linear(params['hidden_dim_2'], params['output_dim'])
|
892 |
+
self.dropout = nn.Dropout(params['dropout_rate'])
|
893 |
+
|
894 |
+
def forward(self, x):
|
895 |
+
x = F.relu(self.fc1(x))
|
896 |
+
x = self.dropout(x)
|
897 |
+
x = F.relu(self.fc2(x))
|
898 |
+
x = self.dropout(x)
|
899 |
+
return self.fc3(x) # Возвращаем выходный размер равный input_size
|
900 |
+
|
901 |
+
# Определение модели LSTM
|
902 |
+
class LSTMPredictor(nn.Module):
|
903 |
+
def __init__(self, params):
|
904 |
+
super(LSTMPredictor, self).__init__()
|
905 |
+
self.lstm = nn.LSTM(params['input_size'], params['hidden_size'], params['num_layers'],
|
906 |
+
batch_first=True, dropout=params['dropout'])
|
907 |
+
self.fc = nn.Linear(params['hidden_size'], 1)
|
908 |
+
|
909 |
+
def forward(self, x):
|
910 |
+
lstm_out, _ = self.lstm(x)
|
911 |
+
last_hidden = lstm_out[:, -1, :]
|
912 |
+
return self.fc(last_hidden)
|
913 |
+
|
914 |
+
# Определение модели EmotionAwareness с GNN и LSTM
|
915 |
+
class EmotionAwarenessModel(nn.Module):
|
916 |
+
def __init__(self, gnn_params, lstm_params):
|
917 |
+
super(EmotionAwarenessModel, self).__init__()
|
918 |
+
self.gnn = GraphNeuralNetwork(gnn_params)
|
919 |
+
self.lstm = LSTMPredictor(lstm_params)
|
920 |
+
|
921 |
+
def forward(self, x):
|
922 |
+
gnn_out = self.gnn(x) # GNN output: shape (batch_size, input_size)
|
923 |
+
gnn_out = gnn_out.unsqueeze(1) # Add sequence length dimension: shape (batch_size, 1, input_size)
|
924 |
+
return self.lstm(gnn_out) # Pass to LSTM
|
925 |
+
|
926 |
+
# Создание модели
|
927 |
+
model = EmotionAwarenessModel(gnn_params, lstm_params)
|
928 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
929 |
+
|
930 |
+
# Пример данных (batch_size, input_size)
|
931 |
+
x = torch.randn(batch_size, input_size) # Should be (batch_size, input_size)
|
932 |
+
target = torch.randn(batch_size, 1) # Целевое значение
|
933 |
+
|
934 |
+
# Обучение модели
|
935 |
+
for epoch in range(num_epochs):
|
936 |
+
model.train()
|
937 |
+
optimizer.zero_grad()
|
938 |
+
|
939 |
+
# Прямой проход
|
940 |
+
output = model(x)
|
941 |
+
|
942 |
+
# Расчет потерь
|
943 |
+
loss = F.mse_loss(output, target)
|
944 |
+
loss.backward()
|
945 |
+
|
946 |
+
# Обновление параметров
|
947 |
+
optimizer.step()
|
948 |
+
|
949 |
+
print(f'Epoch {epoch + 1}, Loss: {loss.item():.4f}')
|
950 |
+
|
951 |
+
"""# ***NEW METHOD MACHINE LEARNING***"""
|
952 |
+
|
953 |
+
import numpy as np
|
954 |
+
import torch
|
955 |
+
import torch.nn as nn
|
956 |
+
import torch.optim as optim
|
957 |
+
from torch_geometric.nn import GCNConv
|
958 |
+
from torch_geometric.data import Data
|
959 |
+
import torch.nn.functional as F
|
960 |
+
|
961 |
+
# Линейная регрессия для эталонного решения
|
962 |
+
class LinearRegressionModel:
|
963 |
+
def init(self):
|
964 |
+
self.model = LinearRegression()
|
965 |
+
|
966 |
+
def fit(self, X, y):
|
967 |
+
self.model.fit(X, y)
|
968 |
+
|
969 |
+
def predict(self, X):
|
970 |
+
return self.model.predict(X)
|
971 |
+
|
972 |
+
# Графовая нейросеть для подбора альтернативных решений
|
973 |
+
class GraphNeuralNetwork(nn.Module):
|
974 |
+
def init(self, in_channels, out_channels):
|
975 |
+
super(GraphNeuralNetwork, self).init()
|
976 |
+
self.conv1 = GCNConv(in_channels, 16)
|
977 |
+
self.conv2 = GCNConv(16, out_channels)
|
978 |
+
|
979 |
+
def forward(self, data):
|
980 |
+
x, edge_index = data.x, data.edge_index
|
981 |
+
x = self.conv1(x, edge_index)
|
982 |
+
x = F.relu(x)
|
983 |
+
x = self.conv2(x, edge_index)
|
984 |
+
return x
|
985 |
+
|
986 |
+
# Q-обучение с PPO
|
987 |
+
class QLearningWithPPO:
|
988 |
+
def init(self, state_dim, action_dim, lr=0.001, gamma=0.99):
|
989 |
+
self.q_net = nn.Linear(state_dim, action_dim)
|
990 |
+
self.optimizer = optim.Adam(self.q_net.parameters(), lr=lr)
|
991 |
+
self.gamma = gamma
|
992 |
+
self.eps_clip = 0.2
|
993 |
+
|
994 |
+
def get_action(self, state):
|
995 |
+
q_values = self.q_net(state)
|
996 |
+
action = torch.argmax(q_values).item()
|
997 |
+
return action
|
998 |
+
|
999 |
+
def update(self, state, action, reward, next_state):
|
1000 |
+
q_values = self.q_net(state)
|
1001 |
+
q_next = self.q_net(next_state).detach()
|
1002 |
+
|
1003 |
+
target = reward + self.gamma * torch.max(q_next)
|
1004 |
+
loss = F.mse_loss(q_values[action], target)
|
1005 |
+
|
1006 |
+
self.optimizer.zero_grad()
|
1007 |
+
loss.backward()
|
1008 |
+
self.optimizer.step()
|
1009 |
+
|
1010 |
+
# Метод обучения логики
|
1011 |
+
def logic_learning_with_q_ppo(dataset, num_alternatives=10):
|
1012 |
+
lin_model = LinearRegressionModel()
|
1013 |
+
X, y = dataset[:, :-1], dataset[:, -1]
|
1014 |
+
lin_model.fit(X, y)
|
1015 |
+
base_solution = lin_model.predict(X)
|
1016 |
+
|
1017 |
+
gnn_model = GraphNeuralNetwork(in_channels=1, out_channels=1)
|
1018 |
+
optimizer_gnn = optim.Adam(gnn_model.parameters(), lr=0.01)
|
1019 |
+
q_ppo = QLearningWithPPO(state_dim=1, action_dim=num_alternatives)
|
1020 |
+
|
1021 |
+
edge_index = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)
|
1022 |
+
x = torch.tensor(base_solution, dtype=torch.float).view(-1, 1)
|
1023 |
+
data = Data(x=x, edge_index=edge_index)
|
1024 |
+
|
1025 |
+
for i in range(num_alternatives):
|
1026 |
+
state = torch.tensor([i], dtype=torch.float)
|
1027 |
+
action = q_ppo.get_action(state)
|
1028 |
+
|
1029 |
+
# Тренировка графовой сети
|
1030 |
+
gnn_model.train()
|
1031 |
+
for epoch in range(50):
|
1032 |
+
optimizer_gnn.zero_grad()
|
1033 |
+
out = gnn_model(data)
|
1034 |
+
loss = F.mse_loss(out, x)
|
1035 |
+
loss.backward()
|
1036 |
+
optimizer_gnn.step()
|
1037 |
+
|
1038 |
+
solution = out.detach().numpy().flatten()
|
1039 |
+
reward = -np.abs(base_solution - solution).sum()
|
1040 |
+
|
1041 |
+
next_state = torch.tensor([i + 1], dtype=torch.float)
|
1042 |
+
q_ppo.update(state, action, reward, next_state)
|
1043 |
+
|
1044 |
+
print(f"Alternative solution {i+1}: reward = {reward}")
|
1045 |
+
|
1046 |
+
return solution
|
1047 |
+
|
1048 |
+
"""# ***COMBINED MODELS LIBERALMIND***"""
|
1049 |
+
|
1050 |
+
import numpy as np
|
1051 |
+
import torch
|
1052 |
+
import torch.nn as nn
|
1053 |
+
import torch.optim as optim
|
1054 |
+
from torch_geometric.nn import GCNConv
|
1055 |
+
from torch_geometric.data import Data
|
1056 |
+
import torch.nn.functional as F
|
1057 |
+
from sklearn.linear_model import LinearRegression
|
1058 |
+
|
1059 |
+
# ��инейная регрессия для эталонного решения
|
1060 |
+
class LinearRegressionModel:
|
1061 |
+
def __init__(self, params):
|
1062 |
+
self.params = params
|
1063 |
+
self.model = LinearRegression(
|
1064 |
+
fit_intercept=params['fit_intercept'],
|
1065 |
+
copy_X=params['copy_X'],
|
1066 |
+
n_jobs=params['n_jobs']
|
1067 |
+
)
|
1068 |
+
|
1069 |
+
def fit(self, X, y):
|
1070 |
+
if self.params.get('normalize', False):
|
1071 |
+
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
|
1072 |
+
self.model.fit(X, y)
|
1073 |
+
|
1074 |
+
def predict(self, X):
|
1075 |
+
return self.model.predict(X)
|
1076 |
+
|
1077 |
+
# Графовая нейросеть для подбора альтернативных решений
|
1078 |
+
class GraphNeuralNetwork(nn.Module):
|
1079 |
+
def __init__(self, params):
|
1080 |
+
super(GraphNeuralNetwork, self).__init__()
|
1081 |
+
self.conv1 = GCNConv(params['in_channels'], params['hidden_dim1'])
|
1082 |
+
self.conv2 = GCNConv(params['hidden_dim1'], params['hidden_dim2'])
|
1083 |
+
self.conv3 = GCNConv(params['hidden_dim2'], params['out_channels'])
|
1084 |
+
self.dropout = params['dropout']
|
1085 |
+
|
1086 |
+
def forward(self, data):
|
1087 |
+
x, edge_index = data.x, data.edge_index
|
1088 |
+
x = self.conv1(x, edge_index)
|
1089 |
+
x = F.relu(x)
|
1090 |
+
x = F.dropout(x, p=self.dropout, training=self.training)
|
1091 |
+
x = self.conv2(x, edge_index)
|
1092 |
+
x = F.relu(x)
|
1093 |
+
x = F.dropout(x, p=self.dropout, training=self.training)
|
1094 |
+
x = self.conv3(x, edge_index)
|
1095 |
+
return x
|
1096 |
+
|
1097 |
+
# Q-обучение с PPO
|
1098 |
+
class QLearningWithPPO:
|
1099 |
+
def __init__(self, state_dim, action_dim, lr=0.001, gamma=0.99):
|
1100 |
+
self.q_net = nn.Linear(state_dim, action_dim)
|
1101 |
+
self.optimizer = optim.Adam(self.q_net.parameters(), lr=lr)
|
1102 |
+
self.gamma = gamma
|
1103 |
+
|
1104 |
+
def get_action(self, state):
|
1105 |
+
q_values = self.q_net(state)
|
1106 |
+
action = torch.argmax(q_values).item()
|
1107 |
+
return action
|
1108 |
+
|
1109 |
+
def update(self, state, action, reward, next_state):
|
1110 |
+
q_values = self.q_net(state)
|
1111 |
+
q_next = self.q_net(next_state).detach()
|
1112 |
+
|
1113 |
+
target = reward + self.gamma * torch.max(q_next)
|
1114 |
+
loss = F.mse_loss(q_values[action], target)
|
1115 |
+
|
1116 |
+
self.optimizer.zero_grad()
|
1117 |
+
loss.backward()
|
1118 |
+
self.optimizer.step()
|
1119 |
+
|
1120 |
+
# Определение базовых нейросетей для примера
|
1121 |
+
class CreativeNet(nn.Module):
|
1122 |
+
def __init__(self):
|
1123 |
+
super(CreativeNet, self).__init__()
|
1124 |
+
self.fc = nn.Linear(10, 20)
|
1125 |
+
|
1126 |
+
def forward(self, x):
|
1127 |
+
return torch.relu(self.fc(x))
|
1128 |
+
|
1129 |
+
class LogicNet(nn.Module):
|
1130 |
+
def __init__(self):
|
1131 |
+
super(LogicNet, self).__init__()
|
1132 |
+
self.fc = nn.Linear(20, 30)
|
1133 |
+
|
1134 |
+
def forward(self, x):
|
1135 |
+
return torch.relu(self.fc(x))
|
1136 |
+
|
1137 |
+
class MathNet(nn.Module):
|
1138 |
+
def __init__(self):
|
1139 |
+
super(MathNet, self).__init__()
|
1140 |
+
self.fc = nn.Linear(30, 40)
|
1141 |
+
|
1142 |
+
def forward(self, x):
|
1143 |
+
return torch.relu(self.fc(x))
|
1144 |
+
|
1145 |
+
# Общий класс для объединенной модели
|
1146 |
+
class CombinedModel(nn.Module):
|
1147 |
+
def __init__(self, gnn_params):
|
1148 |
+
super(CombinedModel, self).__init__()
|
1149 |
+
self.creative_net = CreativeNet()
|
1150 |
+
self.logic_net = LogicNet()
|
1151 |
+
self.math_net = MathNet()
|
1152 |
+
self.gnn_model = GraphNeuralNetwork(gnn_params)
|
1153 |
+
|
1154 |
+
def forward(self, x, data):
|
1155 |
+
# Обработка через сети
|
1156 |
+
x = self.creative_net(x) # Первый этап - творчество
|
1157 |
+
x = self.logic_net(x) # Второй этап - логика
|
1158 |
+
x = self.math_net(x) # Третий этап - математика
|
1159 |
+
|
1160 |
+
# Обработка через графовую нейросеть
|
1161 |
+
gnn_output = self.gnn_model(data)
|
1162 |
+
|
1163 |
+
return gnn_output # Возвращаем выход графовой нейросети
|
1164 |
+
|
1165 |
+
# Метод обучения логики с использованием Q-обучения и графовой нейросети
|
1166 |
+
def logic_learning_with_q_ppo(dataset, num_alternatives=10):
|
1167 |
+
# Гиперпараметры для линейной регрессии
|
1168 |
+
lin_params = {
|
1169 |
+
'fit_intercept': True,
|
1170 |
+
'copy_X': True,
|
1171 |
+
'n_jobs': -1,
|
1172 |
+
'normalize': False, # Опция для нормализации данных, обработается в методе fit
|
1173 |
+
}
|
1174 |
+
|
1175 |
+
# Гиперпараметры для графовой нейросети
|
1176 |
+
gnn_params = {
|
1177 |
+
'in_channels': 1,
|
1178 |
+
'out_channels': 1,
|
1179 |
+
'hidden_dim1': 16,
|
1180 |
+
'hidden_dim2': 32,
|
1181 |
+
'dropout': 0.2,
|
1182 |
+
}
|
1183 |
+
|
1184 |
+
# Инициализация линейной регрессии и объединенной модели
|
1185 |
+
lin_model = LinearRegressionModel(lin_params)
|
1186 |
+
X, y = dataset[:, :-1], dataset[:, -1]
|
1187 |
+
lin_model.fit(X, y)
|
1188 |
+
base_solution = lin_model.predict(X)
|
1189 |
+
|
1190 |
+
q_ppo = QLearningWithPPO(state_dim=1, action_dim=num_alternatives)
|
1191 |
+
|
1192 |
+
# Создание графа
|
1193 |
+
edge_index = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)
|
1194 |
+
x = torch.tensor(base_solution, dtype=torch.float).view(-1, 1)
|
1195 |
+
data = Data(x=x, edge_index=edge_index)
|
1196 |
+
|
1197 |
+
combined_model = CombinedModel(gnn_params)
|
1198 |
+
|
1199 |
+
for i in range(num_alternatives):
|
1200 |
+
state = torch.tensor([i], dtype=torch.float)
|
1201 |
+
action = q_ppo.get_action(state)
|
1202 |
+
|
1203 |
+
# Тренировка графовой сети
|
1204 |
+
combined_model.train()
|
1205 |
+
optimizer_gnn = optim.Adam(combined_model.parameters(), lr=0.01)
|
1206 |
+
for epoch in range(50):
|
1207 |
+
optimizer_gnn.zero_grad()
|
1208 |
+
out = combined_model(torch.tensor(X, dtype=torch.float), data) # Передача данных через объединенную модель
|
1209 |
+
loss = F.mse_loss(out, x)
|
1210 |
+
loss.backward()
|
1211 |
+
optimizer_gnn.step()
|
1212 |
+
|
1213 |
+
solution = out.detach().numpy().flatten()
|
1214 |
+
reward = -np.abs(base_solution - solution).sum()
|
1215 |
+
|
1216 |
+
next_state = torch.tensor([i + 1], dtype=torch.float)
|
1217 |
+
q_ppo.update(state, action, reward, next_state)
|
1218 |
+
|
1219 |
+
print(f"Alternative solution {i + 1}: reward = {reward}")
|
1220 |
+
|
1221 |
+
return solution
|
1222 |
+
|
1223 |
+
# Пример данных
|
1224 |
+
dataset = np.random.rand(100, 11) # Пример: 100 примеров с 10 признаками и 1 целевой переменной
|
1225 |
+
solutions = logic_learning_with_q_ppo(dataset)
|
1226 |
+
|
1227 |
+
# Создание объединенной модели и пример данных для входа
|
1228 |
+
combined_model = CombinedModel({
|
1229 |
+
'in_channels': 1,
|
1230 |
+
'out_channels': 1,
|
1231 |
+
'hidden_dim1': 16,
|
1232 |
+
'hidden_dim2': 32,
|
1233 |
+
'dropout': 0.2,
|
1234 |
+
})
|
1235 |
+
|
1236 |
+
input_data = torch.randn(1, 10)
|
1237 |
+
dummy_data = Data(x=input_data.view(-1, 1), edge_index=torch.tensor([[0, 1], [1, 0]], dtype=torch.long))
|
1238 |
+
output = combined_model(input_data, dummy_data) # Передача dummy_data для GNN
|
1239 |
+
print("Output:", output)
|
1240 |
+
|
1241 |
+
import random
|
1242 |
+
|
1243 |
+
class QLearningWithPPO:
|
1244 |
+
def init(self, state_dim, action_dim, lr=0.001, gamma=0.99, epsilon=0.1):
|
1245 |
+
self.q_net = nn.Linear(state_dim, action_dim)
|
1246 |
+
self.optimizer = optim.Adam(self.q_net.parameters(), lr=lr)
|
1247 |
+
self.gamma = gamma
|
1248 |
+
self.epsilon = epsilon # Для epsilon-greedy стратегии
|
1249 |
+
self.memory = [] # Хранение опытов для обучения
|
1250 |
+
|
1251 |
+
def get_action(self, state):
|
1252 |
+
if random.random() < self.epsilon: # Эpsilon-greedy стратегия
|
1253 |
+
return random.randint(0, self.q_net.out_features - 1)
|
1254 |
+
q_values = self.q_net(state)
|
1255 |
+
action = torch.argmax(q_values).item()
|
1256 |
+
return action
|
1257 |
+
|
1258 |
+
def update(self, batch_size):
|
1259 |
+
if len(self.memory) < batch_size:
|
1260 |
+
return
|
1261 |
+
|
1262 |
+
# Случайный выбор опыта из памяти
|
1263 |
+
experiences = random.sample(self.memory, batch_size)
|
1264 |
+
states, actions, rewards, next_states = zip(*experiences)
|
1265 |
+
|
1266 |
+
states = torch.stack(states)
|
1267 |
+
actions = torch.tensor(actions)
|
1268 |
+
rewards = torch.tensor(rewards)
|
1269 |
+
next_states = torch.stack(next_states)
|
1270 |
+
|
1271 |
+
q_values = self.q_net(states)
|
1272 |
+
q_next = self.q_net(next_states).detach()
|
1273 |
+
|
1274 |
+
target = rewards + self.gamma * torch.max(q_next, dim=1)[0]
|
1275 |
+
loss = F.mse_loss(q_values.gather(1, actions.unsqueeze(1)), target.unsqueeze(1))
|
1276 |
+
|
1277 |
+
self.optimizer.zero_grad()
|
1278 |
+
loss.backward()
|
1279 |
+
self.optimizer.step()
|
1280 |
+
|
1281 |
+
def store_experience(self, state, action, reward, next_state):
|
1282 |
+
self.memory.append((state, action, reward, next_state))
|
1283 |
+
|
1284 |
+
# Метод обучения логики с использованием Q-обучения и графовой нейросети
|
1285 |
+
def logic_learning_with_q_ppo(dataset, num_epochs=100, batch_size=32, num_alternatives=10):
|
1286 |
+
# Гиперпараметры для линейной регрессии
|
1287 |
+
lin_params = {
|
1288 |
+
'fit_intercept': True,
|
1289 |
+
'copy_X': True,
|
1290 |
+
'n_jobs': -1,
|
1291 |
+
'normalize': False,
|
1292 |
+
}
|
1293 |
+
|
1294 |
+
# Инициализация моделей
|
1295 |
+
lin_reg_model = LinearRegressionModel()
|
1296 |
+
lin_reg_model.init(lin_params)
|
1297 |
+
|
1298 |
+
|
1299 |
+
|
1300 |
+
# Инициализация графовой нейросети и Q-обучения с PPO
|
1301 |
+
gnn_params = {
|
1302 |
+
'in_channels': data.num_node_features,
|
1303 |
+
'hidden_dim1': 16,
|
1304 |
+
'hidden_dim2': 8,
|
1305 |
+
'out_channels': 4,
|
1306 |
+
'dropout': 0.5,
|
1307 |
+
}
|
1308 |
+
gnn_model = GraphNeuralNetwork(gnn_params)
|
1309 |
+
q_ppo = QLearningWithPPO(state_dim=10, action_dim=4) # Пример размерности состояния и действия
|
1310 |
+
|
1311 |
+
# Основной цикл обучения
|
1312 |
+
for epoch in range(num_epochs):
|
1313 |
+
state = torch.tensor(X, dtype=torch.float32) # Преобразуем X в тензор
|
1314 |
+
action = q_ppo.get_action(state) # Получаем действие
|
1315 |
+
reward = random.random() # Пример получения вознаграждения (это должно быть заменено на реальную логику)
|
1316 |
+
next_state = state # В реальном сценарии next_state должен изменяться
|
1317 |
+
|
1318 |
+
# ��охраняем опыт
|
1319 |
+
q_ppo.store_experience(state, action, reward, next_state)
|
1320 |
+
|
1321 |
+
# Обновляем модель каждые batch_size итераций
|
1322 |
+
if (epoch + 1) % batch_size == 0:
|
1323 |
+
q_ppo.update(batch_size)
|
1324 |
+
|
1325 |
+
# Вывод информации о текущем прогрессе
|
1326 |
+
if (epoch + 1) % 10 == 0:
|
1327 |
+
print(f"Эпоха {epoch + 1}/{num_epochs}, Вознаграждение: {reward:.4f}")
|
1328 |
+
|
1329 |
+
# Вывод предсказаний
|
1330 |
+
print("Предсказания линейной регрессии:", y_pred)
|
1331 |
+
print("Выход графовой нейросети:", gnn_model(data))
|
1332 |
+
|
1333 |
+
"""# ***GENERATIVE MODEL***"""
|
1334 |
+
|
1335 |
+
import torch
|
1336 |
+
import torch.nn as nn
|
1337 |
+
from stable_baselines3 import PPO
|
1338 |
+
from gym import Env
|
1339 |
+
from gym.spaces import Box, Discrete
|
1340 |
+
from datasets import load_dataset
|
1341 |
+
|
1342 |
+
# Модель творчества
|
1343 |
+
class CreativeNet(nn.Module):
|
1344 |
+
def init(self):
|
1345 |
+
super(CreativeNet, self).init()
|
1346 |
+
self.fc = nn.Linear(32, 64)
|
1347 |
+
|
1348 |
+
def forward(self, x):
|
1349 |
+
return torch.relu(self.fc(x))
|
1350 |
+
|
1351 |
+
# Модель логики
|
1352 |
+
class LogicNet(nn.Module):
|
1353 |
+
def init(self):
|
1354 |
+
super(LogicNet, self).init()
|
1355 |
+
self.fc = nn.Linear(64, 128)
|
1356 |
+
|
1357 |
+
def forward(self, x):
|
1358 |
+
return torch.relu(self.fc(x))
|
1359 |
+
|
1360 |
+
# Математическая модель
|
1361 |
+
class MathNet(nn.Module):
|
1362 |
+
def init(self):
|
1363 |
+
super(MathNet, self).init()
|
1364 |
+
self.fc = nn.Linear(128, 32)
|
1365 |
+
|
1366 |
+
def forward(self, x):
|
1367 |
+
return torch.relu(self.fc(x))
|
1368 |
+
|
1369 |
+
# Объединённая модель
|
1370 |
+
class CombinedModel(nn.Module):
|
1371 |
+
def init(self):
|
1372 |
+
super(CombinedModel, self).init()
|
1373 |
+
self.creative_net = CreativeNet()
|
1374 |
+
self.logic_net = LogicNet()
|
1375 |
+
self.math_net = MathNet()
|
1376 |
+
|
1377 |
+
def forward(self, x):
|
1378 |
+
x = self.creative_net(x)
|
1379 |
+
x = self.logic_net(x)
|
1380 |
+
x = self.math_net(x)
|
1381 |
+
return x
|
1382 |
+
|
1383 |
+
# Среда обучения
|
1384 |
+
class CustomEnv(Env):
|
1385 |
+
def init(self, model, dataset):
|
1386 |
+
super(CustomEnv, self).init()
|
1387 |
+
self.model = model
|
1388 |
+
self.dataset = dataset
|
1389 |
+
self.action_space = Discrete(3)
|
1390 |
+
self.observation_space = Box(low=0, high=1, shape=(32,), dtype=torch.float32)
|
1391 |
+
self.current_index = 0
|
1392 |
+
|
1393 |
+
def reset(self):
|
1394 |
+
self.current_index = 0
|
1395 |
+
return self._get_observation()
|
1396 |
+
|
1397 |
+
def step(self, action):
|
1398 |
+
observation = self._get_observation()
|
1399 |
+
input_tensor = torch.tensor(observation, dtype=torch.float32).unsqueeze(0)
|
1400 |
+
model_output = self.model(input_tensor).squeeze(0).detach().numpy()
|
1401 |
+
|
1402 |
+
# Логика вознаграждения на основе действий и вывода модели
|
1403 |
+
reward = -1 if action != model_output.argmax() else 1
|
1404 |
+
self.current_index += 1
|
1405 |
+
done = self.current_index >= len(self.dataset)
|
1406 |
+
return observation, reward, done, {}
|
1407 |
+
|
1408 |
+
def _get_observation(self):
|
1409 |
+
return torch.tensor(self.dataset[self.current_index], dtype=torch.float32).numpy()
|
1410 |
+
|
1411 |
+
|
1412 |
+
# Загрузка датасета
|
1413 |
+
keyword = "/content/dataset/anthropic_hh_golden-test.arrow"
|
1414 |
+
dataset = load_dataset(keyword)["train"][:10]
|
1415 |
+
input_size = len(dataset[0])
|
1416 |
+
|
1417 |
+
# Инициализация модели и среды
|
1418 |
+
model = CombinedModel()
|
1419 |
+
env = CustomEnv(model, dataset)
|
1420 |
+
|
1421 |
+
# Настройка PPO
|
1422 |
+
ppo_model = PPO("MlpPolicy", env, verbose=1)
|
1423 |
+
ppo_model.learn(total_timesteps=10000)
|
1424 |
+
|
1425 |
+
# Генерация ответа
|
1426 |
+
def generate_response(model, input_data):
|
1427 |
+
input_tensor = torch.tensor(input_data, dtype=torch.float32).unsqueeze(0)
|
1428 |
+
output = model(input_tensor).squeeze(0).detach().numpy()
|
1429 |
+
return output.argmax()
|
1430 |
+
|
1431 |
+
# Пример генерации
|
1432 |
+
example_input = torch.rand(32).numpy()
|
1433 |
+
generated_response = generate_response(model, example_input)
|
1434 |
+
print("Generated response:", generated_response)
|
1435 |
+
|
1436 |
+
import torch
|
1437 |
+
import torch.nn as nn
|
1438 |
+
import torch.optim as optim
|
1439 |
+
from torch_geometric.data import Data
|
1440 |
+
from datasets import load_dataset
|
1441 |
+
from sklearn.preprocessing import StandardScaler
|
1442 |
+
import numpy as np
|
1443 |
+
from tqdm import tqdm
|
1444 |
+
|
1445 |
+
# Универсальная объединённая модель
|
1446 |
+
class CombinedModel(nn.Module):
|
1447 |
+
def init(self, input_size, hidden_size, output_size):
|
1448 |
+
super(CombinedModel, self).init()
|
1449 |
+
# Энкодер на основе LSTM
|
1450 |
+
self.encoder = nn.LSTM(input_size, hidden_size, batch_first=True)
|
1451 |
+
# Графовая нейросеть
|
1452 |
+
self.gnn_fc1 = nn.Linear(hidden_size, 64)
|
1453 |
+
self.gnn_fc2 = nn.Linear(64, hidden_size)
|
1454 |
+
# Декодер на основе LSTM
|
1455 |
+
self.decoder = nn.LSTM(hidden_size, output_size, batch_first=True)
|
1456 |
+
|
1457 |
+
def forward(self, x, edge_index=None):
|
1458 |
+
# Энкодинг последовательностей
|
1459 |
+
x, _ = self.encoder(x)
|
1460 |
+
x = x[:, -1, :] # Используем последний выход
|
1461 |
+
# Обработка через GNN
|
1462 |
+
x = torch.relu(self.gnn_fc1(x))
|
1463 |
+
x = torch.relu(self.gnn_fc2(x))
|
1464 |
+
# Декодинг
|
1465 |
+
x = x.unsqueeze(1).repeat(1, 10, 1) # Растягиваем для LSTM-декодера
|
1466 |
+
x, _ = self.decoder(x)
|
1467 |
+
return x
|
1468 |
+
|
1469 |
+
# Функция загрузки и предобработки датасета
|
1470 |
+
def preprocess_dataset(dataset_name):
|
1471 |
+
dataset = load_dataset(dataset_name)
|
1472 |
+
# Преобразуем данные в numpy (или используем ваш подход)
|
1473 |
+
if 'train' in dataset:
|
1474 |
+
data = np.array(dataset['train'])
|
1475 |
+
else:
|
1476 |
+
data = np.array(dataset['data'])
|
1477 |
+
# Масштабирование
|
1478 |
+
scaler = StandardScaler()
|
1479 |
+
scaled_data = scaler.fit_transform(data)
|
1480 |
+
return torch.tensor(scaled_data, dtype=torch.float32)
|
1481 |
+
|
1482 |
+
# Обучение модели
|
1483 |
+
def train_model(model, dataset, epochs=10, batch_size=32, learning_rate=1e-4):
|
1484 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
1485 |
+
loss_fn = nn.MSELoss()
|
1486 |
+
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
1487 |
+
|
1488 |
+
for epoch in range(epochs):
|
1489 |
+
total_loss = 0
|
1490 |
+
for batch in tqdm(dataloader, desc=f"Epoch {epoch + 1}/{epochs}"):
|
1491 |
+
inputs = batch[:, :-1].unsqueeze(1) # Последний столбец - целевая переменная
|
1492 |
+
targets = batch[:, -1].unsqueeze(1)
|
1493 |
+
|
1494 |
+
optimizer.zero_grad()
|
1495 |
+
outputs = model(inputs)
|
1496 |
+
loss = loss_fn(outputs.squeeze(), targets)
|
1497 |
+
loss.backward()
|
1498 |
+
optimizer.step()
|
1499 |
+
total_loss += loss.item()
|
1500 |
+
print(f"Loss: {total_loss / len(dataloader):.4f}")
|
1501 |
+
|
1502 |
+
# Пример использования
|
1503 |
+
if name == "main":
|
1504 |
+
# Параметры модели
|
1505 |
+
input_size = 10
|
1506 |
+
hidden_size = 128
|
1507 |
+
output_size = 1
|
1508 |
+
|
1509 |
+
# Инициализация модели
|
1510 |
+
model = CombinedModel(input_size, hidden_size, output_size)
|
1511 |
+
|
1512 |
+
# Загрузка и предобработка датасета
|
1513 |
+
dataset_name = "your_dataset_name" # Укажите название датасета
|
1514 |
+
dataset = preprocess_dataset(dataset_name)
|
1515 |
+
|
1516 |
+
# Обучение модели
|
1517 |
+
train_model(model, dataset)
|
1518 |
+
|
1519 |
+
import torch
|
1520 |
+
import torch.nn as nn
|
1521 |
+
import torch.optim as optim
|
1522 |
+
import numpy as np
|
1523 |
+
from sklearn.ensemble import RandomForestClassifier
|
1524 |
+
from stable_baselines3 import PPO
|
1525 |
+
from gym import Env
|
1526 |
+
from gym.spaces import Box, Discrete
|
1527 |
+
import pandas as pd
|
1528 |
+
import os
|
1529 |
+
|
1530 |
+
# *ШАГ 1: Объединение трех моделей в одну*
|
1531 |
+
|
1532 |
+
class UnifiedModel(nn.Module):
|
1533 |
+
def init(self, input_size, hidden_size, output_size):
|
1534 |
+
super(UnifiedModel, self).init()
|
1535 |
+
# LSTM-энкодер
|
1536 |
+
self.encoder = nn.LSTM(input_size, hidden_size, batch_first=True)
|
1537 |
+
# Логическая модель
|
1538 |
+
self.logic_fc = nn.Sequential(
|
1539 |
+
nn.Linear(hidden_size, hidden_size * 2),
|
1540 |
+
nn.ReLU(),
|
1541 |
+
nn.Linear(hidden_size * 2, hidden_size)
|
1542 |
+
)
|
1543 |
+
# LSTM-декодер
|
1544 |
+
self.decoder = nn.LSTM(hidden_size, output_size, batch_first=True)
|
1545 |
+
|
1546 |
+
def forward(self, x):
|
1547 |
+
# Проходим через LSTM-энкодер
|
1548 |
+
x, _ = self.encoder(x)
|
1549 |
+
x = x[:, -1, :] # Используем последний выход
|
1550 |
+
# Пропускаем через логическую модель
|
1551 |
+
x = self.logic_fc(x)
|
1552 |
+
# Добавляем измерение времени для декодера
|
1553 |
+
x = x.unsqueeze(1).repeat(1, 10, 1)
|
1554 |
+
x, _ = self.decoder(x)
|
1555 |
+
return x
|
1556 |
+
|
1557 |
+
# *ШАГ 2: Работа с файлами любого формата*
|
1558 |
+
|
1559 |
+
def load_dataset(file_path):
|
1560 |
+
# Определяем тип файла
|
1561 |
+
ext = os.path.splitext(file_path)[1].lower()
|
1562 |
+
if ext == '.csv':
|
1563 |
+
data = pd.read_csv(file_path)
|
1564 |
+
elif ext in ['.xls', '.xlsx']:
|
1565 |
+
data = pd.read_excel(file_path)
|
1566 |
+
elif ext == '.json':
|
1567 |
+
data = pd.read_json(file_path)
|
1568 |
+
elif ext == '.txt':
|
1569 |
+
data = pd.read_csv(file_path, delimiter='\t')
|
1570 |
+
else:
|
1571 |
+
raise ValueError("Формат файла не поддерживается")
|
1572 |
+
|
1573 |
+
# Преобразуем в NumPy массив и масштабируем
|
1574 |
+
data = data.select_dtypes(include=[np.number]).dropna() # Оставляем только числовые данные
|
1575 |
+
return torch.tensor(data.values, dtype=torch.float32)
|
1576 |
+
|
1577 |
+
# *ШАГ 3: RLCF и PPO обучение*
|
1578 |
+
|
1579 |
+
# Класс среды для PPO
|
1580 |
+
class CustomEnv(Env):
|
1581 |
+
def init(self, data):
|
1582 |
+
super(CustomEnv, self).init()
|
1583 |
+
self.data = data
|
1584 |
+
self.current_step = 0
|
1585 |
+
self.action_space = Discrete(3) # Пример: 3 действия
|
1586 |
+
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(data.shape[1],), dtype=np.float32)
|
1587 |
+
|
1588 |
+
def reset(self):
|
1589 |
+
self.current_step = 0
|
1590 |
+
return self.data[self.current_step]
|
1591 |
+
|
1592 |
+
def step(self, action):
|
1593 |
+
self.current_step += 1
|
1594 |
+
reward = np.random.random() # Пример: случайная награда
|
1595 |
+
done = self.current_step >= len(self.data)
|
1596 |
+
return self.data[self.current_step % len(self.data)], reward, done, {}
|
1597 |
+
|
1598 |
+
# Функция RLCF
|
1599 |
+
def train_with_rlcf(data):
|
1600 |
+
# Random Forest классификатор
|
1601 |
+
rf = RandomForestClassifier(n_estimators=100)
|
1602 |
+
X, y = data[:, :-1], data[:, -1]
|
1603 |
+
rf.fit(X, y)
|
1604 |
+
feature_importances = rf.feature_importances_
|
1605 |
+
return feature_importances
|
1606 |
+
|
1607 |
+
# Функция PPO обучения
|
1608 |
+
def train_with_ppo(data):
|
1609 |
+
env = CustomEnv(data)
|
1610 |
+
model = PPO("MlpPolicy", env, verbose=1)
|
1611 |
+
model.learn(total_timesteps=10000)
|
1612 |
+
return model
|
1613 |
+
|
1614 |
+
# *ШАГ 4: Интеграция с Google Colab*
|
1615 |
+
|
1616 |
+
def main():
|
1617 |
+
# Ввод пути к файлу
|
1618 |
+
file_path = input("Введите путь к файлу в директории Google Colab: ")
|
1619 |
+
|
1620 |
+
# Загрузка датасета
|
1621 |
+
data = load_dataset(file_path)
|
1622 |
+
print(f"Датасет загружен! Размер: {data.shape}")
|
1623 |
+
|
1624 |
+
# Инициализация модели
|
1625 |
+
input_size = data.shape[1] - 1 # Предполагаем, что последний столбец - целевая переменная
|
1626 |
+
hidden_size = 128
|
1627 |
+
output_size = 1
|
1628 |
+
model = UnifiedModel(input_size, hidden_size, output_size)
|
1629 |
+
|
1630 |
+
# RLCF обучение
|
1631 |
+
feature_importances = train_with_rlcf(data)
|
1632 |
+
print("Feature Importances (RLCF):", feature_importances)
|
1633 |
+
|
1634 |
+
# PPO обучение
|
1635 |
+
ppo_model = train_with_ppo(data)
|
1636 |
+
print("PPO обучение завершено!")
|
1637 |
+
|
1638 |
+
import os
|
1639 |
+
import torch
|
1640 |
+
import torch.nn as nn
|
1641 |
+
import torch.optim as optim
|
1642 |
+
import numpy as np
|
1643 |
+
from sklearn.ensemble import RandomForestClassifier
|
1644 |
+
from stable_baselines3 import PPO
|
1645 |
+
from gym import Env
|
1646 |
+
from gym.spaces import Box, Discrete
|
1647 |
+
import pandas as pd
|
1648 |
+
|
1649 |
+
|
1650 |
+
# *ШАГ 1: Объединение трех моделей в одну*
|
1651 |
+
|
1652 |
+
# Модель творчества
|
1653 |
+
class CreativeNet(nn.Module):
|
1654 |
+
def init(self):
|
1655 |
+
super(CreativeNet, self).init()
|
1656 |
+
self.fc = nn.Linear(32, 64)
|
1657 |
+
|
1658 |
+
def forward(self, x):
|
1659 |
+
return torch.relu(self.fc(x))
|
1660 |
+
|
1661 |
+
# Модель логики
|
1662 |
+
class LogicNet(nn.Module):
|
1663 |
+
def init(self):
|
1664 |
+
super(LogicNet, self).init()
|
1665 |
+
self.fc = nn.Linear(64, 128)
|
1666 |
+
|
1667 |
+
def forward(self, x):
|
1668 |
+
return torch.relu(self.fc(x))
|
1669 |
+
|
1670 |
+
# Математическая модель
|
1671 |
+
class MathNet(nn.Module):
|
1672 |
+
def init(self):
|
1673 |
+
super(MathNet, self).init()
|
1674 |
+
self.fc = nn.Linear(128, 32)
|
1675 |
+
|
1676 |
+
def forward(self, x):
|
1677 |
+
return torch.relu(self.fc(x))
|
1678 |
+
|
1679 |
+
# Объединённая модель
|
1680 |
+
class CombinedModel(nn.Module):
|
1681 |
+
def init(self):
|
1682 |
+
super(CombinedModel, self).init()
|
1683 |
+
self.creative_net = CreativeNet()
|
1684 |
+
self.logic_net = LogicNet()
|
1685 |
+
self.math_net = MathNet()
|
1686 |
+
|
1687 |
+
def forward(self, x):
|
1688 |
+
x = self.creative_net(x)
|
1689 |
+
x = self.logic_net(x)
|
1690 |
+
x = self.math_net(x)
|
1691 |
+
return x
|
1692 |
+
|
1693 |
+
|
1694 |
+
# *ШАГ 2: Загрузка данных из файла любого формата*
|
1695 |
+
|
1696 |
+
def load_dataset(file_path):
|
1697 |
+
try:
|
1698 |
+
if file_path.endswith(('.csv', '.txt')):
|
1699 |
+
data = pd.read_csv(file_path)
|
1700 |
+
elif file_path.endswith(('.xls', '.xlsx')):
|
1701 |
+
data = pd.read_excel(file_path)
|
1702 |
+
elif file_path.endswith('.json'):
|
1703 |
+
data = pd.read_json(file_path)
|
1704 |
+
else:
|
1705 |
+
raise ValueError(f"Формат файла {file_path} не поддерживается.")
|
1706 |
+
|
1707 |
+
# Оставляем только числовые данные и преобразуем их в Tensor
|
1708 |
+
data = data.select_dtypes(include=[np.number]).dropna()
|
1709 |
+
return torch.tensor(data.values, dtype=torch.float32)
|
1710 |
+
except Exception as e:
|
1711 |
+
print(f"Ошибка при загрузке файла: {e}")
|
1712 |
+
return None
|
1713 |
+
|
1714 |
+
|
1715 |
+
# *ШАГ 3: RLCF и PPO обучение*
|
1716 |
+
|
1717 |
+
# Класс среды для PPO
|
1718 |
+
class CustomEnv(Env):
|
1719 |
+
def init(self, data):
|
1720 |
+
super(CustomEnv, self).init()
|
1721 |
+
self.data = data
|
1722 |
+
self.current_step = 0
|
1723 |
+
self.action_space = Discrete(3)
|
1724 |
+
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(data.shape[1],), dtype=np.float32)
|
1725 |
+
|
1726 |
+
def reset(self):
|
1727 |
+
self.current_step = 0
|
1728 |
+
return self.data[self.current_step]
|
1729 |
+
|
1730 |
+
def step(self, action):
|
1731 |
+
self.current_step += 1
|
1732 |
+
reward = np.random.random() # Пример: случайная награда
|
1733 |
+
done = self.current_step >= len(self.data)
|
1734 |
+
return self.data[self.current_step % len(self.data)], reward, done, {}
|
1735 |
+
|
1736 |
+
# Функция RLCF
|
1737 |
+
def train_with_rlcf(data):
|
1738 |
+
rf = RandomForestClassifier(n_estimators=100)
|
1739 |
+
X, y = data[:, :-1], data[:, -1]
|
1740 |
+
rf.fit(X, y)
|
1741 |
+
return rf.feature_importances_
|
1742 |
+
|
1743 |
+
# Класс среды для PPO
|
1744 |
+
class CustomEnv(Env):
|
1745 |
+
def init(self, data):
|
1746 |
+
super(CustomEnv, self).init()
|
1747 |
+
self.data = data.numpy() # Преобразуем данные в numpy
|
1748 |
+
self.current_step = 0
|
1749 |
+
self.action_space = Discrete(3) # Пример: 3 возможных действия
|
1750 |
+
self.observation_space = Box(
|
1751 |
+
low=-np.inf, high=np.inf, shape=(self.data.shape[1] - 1,), dtype=np.float32
|
1752 |
+
)
|
1753 |
+
|
1754 |
+
def reset(self):
|
1755 |
+
# Сбрасываем текущий шаг
|
1756 |
+
self.current_step = 0
|
1757 |
+
# Возвращаем первое наблюдение (все признаки кроме последнего, который мы предполагаем как целевую переменную)
|
1758 |
+
return self.data[self.current_step, :-1].astype(np.float32)
|
1759 |
+
|
1760 |
+
def step(self, action):
|
1761 |
+
# Генерация случайной награды на основе действия (пример)
|
1762 |
+
reward = float(np.random.random())
|
1763 |
+
# Переход к следующему шагу
|
1764 |
+
self.current_step += 1
|
1765 |
+
# Проверяем, завершён ли эпизод
|
1766 |
+
done = self.current_step >= len(self.data)
|
1767 |
+
# Возвращаем следующее наблюдение, награду, статус завершения и пустой словарь информации
|
1768 |
+
obs = self.data[self.current_step % len(self.data), :-1].astype(np.float32)
|
1769 |
+
return obs, reward, done, {}
|
1770 |
+
|
1771 |
+
def main():
|
1772 |
+
# Ввод пути к файлу
|
1773 |
+
file_path = input("Введите путь к вашему файлу в Google Colab: ").strip()
|
1774 |
+
data = load_dataset(file_path)
|
1775 |
+
|
1776 |
+
if data is None:
|
1777 |
+
print("Не удалось загрузить датасет.")
|
1778 |
+
return
|
1779 |
+
|
1780 |
+
print(f"Датасет успешно загружен! Размер данных: {data.shape}")
|
1781 |
+
|
1782 |
+
# Инициализация объединённой модели
|
1783 |
+
model = CombinedModel()
|
1784 |
+
print("Объединённая модель создана!")
|
1785 |
+
|
1786 |
+
# RLCF обучение
|
1787 |
+
feature_importances = train_with_rlcf(data)
|
1788 |
+
print("Feature Importances (RLCF):", feature_importances)
|
1789 |
+
|
1790 |
+
# PPO обучение
|
1791 |
+
ppo_model = train_with_ppo(data)
|
1792 |
+
print("PPO обучение завершено!")
|
1793 |
+
|
1794 |
+
|
1795 |
+
# Запуск
|
1796 |
+
main()
|