diff --git a/README.md b/README.md index 5e3b213..66bddcb 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,41 @@ [![Python Package Index publish](https://github.com/jung-geun/PSO/actions/workflows/pypi.yml/badge.svg?event=push)](https://github.com/jung-geun/PSO/actions/workflows/pypi.yml) +### 목차 + +> [PSO 알고리즘 구현 및 새로운 시도](#pso-알고리즘-구현-및-새로운-시도)
+> +> [초기 세팅 및 사용 방법](#초기-세팅-및-사용-방법)
+> +> [구조 및 작동 방식](#구조-및-작동-방식)
+> +> [PSO 알고리즘을 이용하여 풀이한 문제들의 정확도](#pso-알고리즘을-이용하여-풀이한-문제들의-정확도)
+> +> [참고 자료](#참고-자료)
+ # PSO 알고리즘 구현 및 새로운 시도 -pso 알고리즘을 사용하여 새로운 학습 방법을 찾는중 입니다 -병렬처리로 사용하는 논문을 찾아보았지만 이보다 더 좋은 방법이 있을 것 같아서 찾아보고 있습니다 - \[1] +pso 알고리즘을 사용하여 새로운 학습 방법을 찾는중 입니다
+병렬처리로 사용하는 논문을 찾아보았지만 이보다 더 좋은 방법이 있을 것 같아서 찾아보고 있습니다 - [[1]](#참고-자료)
-기본 pso 알고리즘의 수식은 다음과 같습니다 +기본 pso 알고리즘의 속도를 구하는 수식은 다음과 같습니다 -> $$V_{id(t+1)} = W_{V_id(t)} + c_1 * r_1 (p_{id(t)} - x_{id(t)}) + c_2 * r_2(p_{gd(t)} - x_{id(t)})$$ +> $$V_{t+1} = W_t + c_1 * r_1 * (Pbest_t - x_t) + c_2 * r_2 * (Gbest_t - x_t)$$ -다음 속도을 구하는 수식입니다 +다음 위치를 업데이트하는 수식입니다 -> $$x_{id(t+1)} = x_{id(t)} + V_{id(t+1)}$$ +> $$x_{t+1} = x_{t} + V_{t+1}$$ -다음 위치를 구하는 수식입니다 +다음과 같은 변수를 사용합니다 -> $$ -> p_{id(t+1)} = -> \begin{cases} -> x_{id(t+1)} & \text{if } f(x_{id(t+1)}) < f(p_{id(t)})\\ -> p_{id(t)} & \text{otherwise} -> \end{cases} -> $$ +> $Pbest_t : 각 파티클의 지역 최적해$
$Gbest_t : 전역 최적해$
$W_t : 가중치$
$c_1, c_2 : 파라미터$
$r_1, r_2 : 랜덤 값$
$x_t : 현재 위치$
$V_{(t+1)} : 다음 속도$
-# 초기 세팅 +pso 알고리즘을 이용하여 keras 모델을 학습하는 방법을 탐구하고 있습니다
+현재는 xor, iris, mnist 문제를 풀어보았으며, xor 문제와 iris 문제는 100%의 정확도를 보이고 있습니다
+mnist 문제는 63%의 정확도를 보이고 있습니다
+ +[xor](#1-xor-문제)
[iris](#2-iris-문제)
[mnist](#3-mnist-문제) + +# 초기 세팅 및 사용 방법 자동으로 conda 환경을 설정하기 위해서는 다음 명령어를 사용합니다 @@ -36,7 +48,7 @@ conda env create -f conda_env/environment.yaml 직접 설치하여 사용할 경우 pso2keras 패키지를 pypi 에서 다운로드 받아서 사용하시기 바랍니다 ```shell -pip install pso2keras==0.1.4 +pip install pso2keras ``` 위의 패키지를 사용하기 위해서는 tensorflow 와 tensorboard 가 설치되어 있어야 합니다 @@ -52,11 +64,9 @@ pso_model.fit(...) Open In Colab -# 현재 진행 상황 +# 구조 및 작동 방식 -## 1. PSO 알고리즘 구현 - -### 파일 구조 +## 파일 구조 ```plain |-- /conda_env # conda 환경 설정 파일 @@ -79,22 +89,20 @@ pso_model.fit(...) |-- requirements.txt # pypi 에서 다운로드 받을 패키지 목록 ``` -pso 라이브러리는 tensorflow 모델을 학습하기 위해 기본 ./metacode/pso_meta.py 코드에서 수정하였습니다 [2] - -## 2. PSO 알고리즘을 이용한 최적화 문제 풀이 +pso 라이브러리는 tensorflow 모델을 학습하기 위해 기본 ./metacode/pso_meta.py 코드에서 수정하였습니다 [[2]](#참고-자료) pso 알고리즘을 이용하여 오차역전파 함수를 최적화 하는 방법을 찾는 중입니다 -### 알고리즘 작동 방식 +## 알고리즘 작동 방식 > 1. 파티클의 위치와 속도를 초기화 한다. > 2. 각 파티클의 점수를 계산한다. > 3. 각 파티클의 지역 최적해와 전역 최적해를 구한다. > 4. 각 파티클의 속도를 업데이트 한다. -## 3. PSO 알고리즘을 이용하여 풀이한 문제들의 정확도 +# PSO 알고리즘을 이용하여 풀이한 문제들의 정확도 -### 1. xor 문제 +## 1. xor 문제 ```python loss = 'mean_squared_error' @@ -129,7 +137,7 @@ best_score = pso_xor.fit( 위의 파라미터 기준 10 세대 근처부터 정확도가 100%가 나오는 것을 확인하였습니다 ![xor](./history_plt/xor_2_10.png) -2. iris 문제 +## 2. iris 문제 ```python loss = 'mean_squared_error' @@ -166,7 +174,7 @@ best_score = pso_iris.fit( 위의 그래프를 보면 epochs 이 늘어나도 정확도와 loss 가 수렴하지 않는것을 보면 파라미터의 이동 속도가 너무 빠르다고 생각합니다 -3. mnist 문제 +## 3. mnist 문제 ```python loss = 'mean_squared_error' @@ -174,11 +182,11 @@ loss = 'mean_squared_error' pso_mnist = Optimizer( model, loss=loss, - n_particles=100, - c0=0.3, - c1=0.5, - w_min=0.4, - w_max=0.7, + n_particles=500, + c0= 0.4, + c1= 0.6, + w_min= 0.5, + w_max= 0.8, negative_swarm=0.1, mutation_swarm=0.2, particle_min=-5, @@ -198,33 +206,35 @@ best_score = pso_mnist.fit( ) ``` -위의 파라미터 기준 현재 정확도 51.84%를 보이고 있습니다 -![mnist_acc](./history_plt/mnist_51.74_acc.png) -![mnist_loss](./history_plt/mnist_51.74_loss.png) +위의 파라미터 기준 현재 정확도 63.84%를 보이고 있습니다 +![mnist_acc](./history_plt/mnist_63.84_acc.png) +![mnist_loss](./history_plt/mnist_63.84_loss.png) -### Trouble Shooting +## Trouble Shooting -> 1. 딥러닝 알고리즘 특성상 weights는 처음 컴파일시 무작위하게 생성된다. weights의 각 지점의 중요도는 매번 무작위로 정해지기에 전역 최적값으로 찾아갈 때 값이 높은 loss를 향해서 상승하는 현상이 나타난다.
+> 1. 딥러닝 알고리즘 특성상 weights는 처음 컴파일시 무작위하게 생성된다. weights의 각 지점의 중요도는 매번 무작위로 정해지기에 전역 최적값으로 찾아갈 때 값이 높은 loss를 향해서 상승하는 현상이 나타난다.
> 따라서 weights의 이동 방법을 더 탐구하거나, weights를 초기화 할때 random 중요도를 좀더 노이즈가 적게 생성하는 방향을 모색해야할 것 같다. -> 고르게 초기화 하기 위해 np.random.uniform 함수를 사용하였습니다 > 2. 지역최적값에 계속 머무르는 조기 수렴 현상이 나타난다. - 30% 정도의 정확도를 가진다 --> 지역최적값에 머무르는 것을 방지하기 위해 negative_swarm, mutation_swarm 파라미터를 추가하였습니다 - 현재 51% 정도의 정확도를 보이고 있습니다 +-> 지역최적값에 머무르는 것을 방지하기 위해 negative_swarm, mutation_swarm 파라미터를 추가하였습니다 - 현재 63% 정도의 정확도를 보이고 있습니다 > 3. 파티클의 수를 늘리면 전역 최적해에 좀더 가까워지는 현상을 발견하였다. 하지만 파티클의 수를 늘리면 메모리 사용량이 기하급수적으로 늘어난다. --> keras 모델을 사용할때 predict, evaluate 함수를 사용하면 메모리 누수가 발생하는 문제를 찾았습니다. 해결방법을 추가로 찾아보는중 입니다. --> 추가로 파티클의 수가 적을때에도 전역 최적해를 쉽게 찾는 방법을 찾는중 입니다 +-> keras 모델을 사용할때 predict, evaluate 함수를 사용하면 메모리 누수가 발생하는 문제를 찾았습니다. 해결방법을 추가로 찾아보는중 입니다. -> 메모리 누수를 획기적으로 줄여 현재는 파티클의 수를 500개에서 1000개까지 증가시켜도 문제가 없습니다.
+-> 추가로 파티클의 수가 적을때에도 전역 최적해를 쉽게 찾는 방법을 찾는중 입니다
+ +> 4. 모델의 크기가 커지면 수렴이 늦어지고 정확도가 떨어지는 현상이 발견되었다. 모델의 크기에 맞는 파라미터를 찾아야할 것 같다. + +> 5. EBPSO 의 방식을 추가로 적용을 하였으나 수식을 잘못 적용을 한것인지 기본 pso 보다 더 떨어지는 정확도를 보이고 있다. (현재 수정중) ### 개인적인 생각 > 머신러닝 분류 방식에 존재하는 random forest 방식을 이용하여, 오차역전파 함수를 최적화 하는 방법이 있을것 같습니다 > > > pso 와 random forest 방식이 매우 유사하다고 생각하여 학습할 때 뿐만 아니라 예측 할 때도 이러한 방식으로 사용할 수 있을 것 같습니다 -> -> 각 # 참고 자료 diff --git a/history_plt/mnist_63.84_acc.png b/history_plt/mnist_63.84_acc.png new file mode 100755 index 0000000..e2081fd Binary files /dev/null and b/history_plt/mnist_63.84_acc.png differ diff --git a/history_plt/mnist_63.84_loss.png b/history_plt/mnist_63.84_loss.png new file mode 100755 index 0000000..5125364 Binary files /dev/null and b/history_plt/mnist_63.84_loss.png differ diff --git a/iris.py b/iris.py index 2e534da..9d34f52 100644 --- a/iris.py +++ b/iris.py @@ -11,7 +11,7 @@ from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.models import Sequential -from pso import Optimizer +from pso import optimizer def make_model(): @@ -42,7 +42,7 @@ x_train, x_test, y_train, y_test = load_data() loss = ["categorical_crossentropy", "mean_squared_error"] -pso_iris = Optimizer( +pso_iris = optimizer( model, loss=loss[1], n_particles=100, @@ -63,7 +63,7 @@ best_score = pso_iris.fit( save_info=True, log=2, log_name="iris", - save_path="./result/iris", + save_path="result/iris", renewal="acc", check_point=25, ) diff --git a/mnist.ipynb b/mnist.ipynb index c420e5e..69b6012 100644 --- a/mnist.ipynb +++ b/mnist.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -19,7 +19,7 @@ "from keras.models import Sequential\n", "from tensorflow import keras\n", "\n", - "from pso import Optimizer\n", + "from pso import optimizer\n", "\n", "\n", "def get_data():\n", @@ -62,7 +62,6 @@ " model.add(Dense(128, activation=\"relu\"))\n", " model.add(Dense(10, activation=\"softmax\"))\n", "\n", - "\n", " return model" ] }, @@ -187,7 +186,7 @@ "]\n", "\n", "\n", - "pso_mnist = Optimizer(\n", + "pso_mnist = optimizer(\n", " model,\n", " loss=loss[0],\n", " n_particles=70,\n", diff --git a/mnist.py b/mnist.py index 9cd3e37..28058d7 100644 --- a/mnist.py +++ b/mnist.py @@ -5,8 +5,6 @@ import sys os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" -import gc - import numpy as np import tensorflow as tf from keras.datasets import mnist @@ -14,7 +12,7 @@ from keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D from keras.models import Sequential from tensorflow import keras -from pso import Optimizer +from pso import optimizer def get_data(): @@ -40,10 +38,10 @@ def get_data_test(): x_test = x_test / 255.0 x_test = x_test.reshape((10000, 28, 28, 1)) - y_test = tf.one_hot(y_test, 10) + y_train, y_test = tf.one_hot(y_train, 10), tf.one_hot(y_test, 10) - x_test = tf.convert_to_tensor(x_test) - y_test = tf.convert_to_tensor(y_test) + x_train, x_test = tf.convert_to_tensor(x_train), tf.convert_to_tensor(x_test) + y_train, y_test = tf.convert_to_tensor(y_train), tf.convert_to_tensor(y_test) print(f"x_test : {x_test[0].shape} | y_test : {y_test[0].shape}") @@ -53,14 +51,14 @@ def get_data_test(): def make_model(): model = Sequential() model.add( - Conv2D(32, kernel_size=(5, 5), activation="relu", input_shape=(28, 28, 1)) + Conv2D(32, kernel_size=(5, 5), activation="sigmoid", input_shape=(28, 28, 1)) ) model.add(MaxPooling2D(pool_size=(3, 3))) - model.add(Conv2D(64, kernel_size=(3, 3), activation="relu")) + model.add(Conv2D(64, kernel_size=(3, 3), activation="sigmoid")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) - model.add(Dense(128, activation="relu")) + model.add(Dense(128, activation="sigmoid")) model.add(Dense(10, activation="softmax")) return model @@ -101,33 +99,34 @@ loss = [ "mean_absolute_percentage_error", ] -rs = random_state() +# rs = random_state() -pso_mnist = Optimizer( +pso_mnist = optimizer( model, - loss=loss[0], - n_particles=500, - c0=0.3, - c1=0.5, - w_min=0.4, - w_max=0.7, + loss="mean_squared_error", + n_particles=990, + c0=0.2, + c1=0.4, + w_min=0.3, + w_max=0.6, negative_swarm=0.1, mutation_swarm=0.3, particle_min=-4, particle_max=4, - random_state=rs, ) best_score = pso_mnist.fit( x_train, y_train, - epochs=250, + epochs=200, save_info=True, log=2, log_name="mnist", save_path="./result/mnist", renewal="acc", check_point=25, + empirical_balance=False, + dispersion=False, ) print("Done!") diff --git a/mnist_tf.py b/mnist_tf.py index 6a05c03..1aa78c7 100644 --- a/mnist_tf.py +++ b/mnist_tf.py @@ -1,7 +1,7 @@ -# %% import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" + import tensorflow as tf gpus = tf.config.experimental.list_physical_devices("GPU") @@ -17,8 +17,6 @@ from keras.datasets import mnist from keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D from keras.models import Sequential -from pso import Optimizer - def get_data(): (x_train, y_train), (x_test, y_test) = mnist.load_data() @@ -62,10 +60,6 @@ x_train, y_train, x_test, y_test = get_data() y_train = tf.one_hot(y_train, 10) y_test = tf.one_hot(y_test, 10) -# model.compile( - # optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"] -# ) - model.compile(optimizer="adam", loss="mse", metrics=["accuracy"]) print("Training model...") @@ -76,17 +70,3 @@ model.evaluate(x_test, y_test, verbose=1) weights = model.get_weights() -for w in weights: - print(w.shape) - print(w) - print(w.min(), w.max()) - -model.save_weights("weights.h5") - -# %% -for w in weights: - print(w.shape) - print(w) - print(w.min(), w.max()) - -# %% diff --git a/pso/__init__.py b/pso/__init__.py index 1962161..46ba2ca 100644 --- a/pso/__init__.py +++ b/pso/__init__.py @@ -1,9 +1,9 @@ -from .optimizer import Optimizer -from .particle import Particle +from .optimizer import Optimizer as optimizer +from .particle import Particle as particle __version__ = "0.1.6" __all__ = [ - "Optimizer", - "Particle", + "optimizer", + "particle", ] diff --git a/pso/optimizer.py b/pso/optimizer.py index 65f0b13..4e1ac5f 100644 --- a/pso/optimizer.py +++ b/pso/optimizer.py @@ -15,8 +15,8 @@ gpus = tf.config.experimental.list_physical_devices("GPU") if gpus: try: tf.config.experimental.set_memory_growth(gpus[0], True) - except RuntimeError as e: - print(e) + except RuntimeError as r: + print(r) class Optimizer: @@ -81,10 +81,13 @@ class Optimizer: self.w_max = w_max # 최대 관성 수치 self.negative_swarm = negative_swarm # 최적해와 반대로 이동할 파티클 비율 - 0 ~ 1 사이의 값 self.mutation_swarm = mutation_swarm # 관성을 추가로 사용할 파티클 비율 - 0 ~ 1 사이의 값 + self.particle_min = particle_min # 가중치 초기화 최소값 + self.particle_max = particle_max self.g_best_score = [0, np.inf] # 최고 점수 - 시작은 0으로 초기화 self.g_best = None # 최고 점수를 받은 가중치 self.g_best_ = None # 최고 점수를 받은 가중치 - 값의 분산을 위한 변수 self.avg_score = 0 # 평균 점수 + self.sigma = 1.0 self.save_path = None # 저장 위치 self.renewal = "acc" @@ -124,14 +127,11 @@ class Optimizer: tf.keras.backend.reset_uids() tf.keras.backend.clear_session() except KeyboardInterrupt: - print("Ctrl + C : Stop Training") - sys.exit(0) + sys.exit("Ctrl + C : Stop Training") except MemoryError: - print("Memory Error : Stop Training") - sys.exit(1) + sys.exit("Memory Error : Stop Training") except Exception as e: - print(e) - sys.exit(1) + sys.exit(e) def __del__(self): del self.model @@ -147,6 +147,7 @@ class Optimizer: del self.g_best del self.g_best_ del self.avg_score + gc.collect() tf.keras.backend.reset_uids() tf.keras.backend.clear_session() @@ -167,9 +168,9 @@ class Optimizer: shape = [] for layer in weights: shape.append(layer.shape) - w_ = layer.reshape(-1) - length.append(len(w_)) - w_gpu = np.append(w_gpu, w_) + w_tmp = layer.reshape(-1) + length.append(len(w_tmp)) + w_gpu = np.append(w_gpu, w_tmp) del weights @@ -191,18 +192,17 @@ class Optimizer: start = 0 for i in range(len(shape)): end = start + length[i] - w_ = weight[start:end] - w_ = np.reshape(w_, shape[i]) - weights.append(w_) + w_tmp = weight[start:end] + w_tmp = np.reshape(w_tmp, shape[i]) + weights.append(w_tmp) start = end - del weight - del shape - del length + del weight, shape, length + del start, end, w_tmp return weights - def f(self, x, y, weights): + def _f(self, x, y, weights): """ EBPSO의 목적함수 (예상) @@ -215,11 +215,16 @@ class Optimizer: (float): 목적 함수 값 """ self.model.set_weights(weights) - score = self.model.evaluate(x, y, verbose=0)[1] - if score > 0: - return 1 / (1 + score) + score = self.model.evaluate(x, y, verbose=0) + if self.renewal == "acc": + score_ = score[1] else: - return 1 + np.abs(score) + score_ = score[0] + + if score_ > 0: + return 1 / (1 + score_) + else: + return 1 + np.abs(score_) def fit( self, @@ -253,6 +258,7 @@ class Optimizer: self.dispersion = dispersion self.renewal = renewal + particle_sum = 0 # x_j try: train_log_dir = "logs/fit/" + self.day if log == 2: @@ -269,17 +275,17 @@ class Optimizer: raise ValueError("save_path is None") else: self.save_path = save_path - if not os.path.exists(save_path): - os.makedirs(save_path, exist_ok=True) + if not os.path.exists(f"{save_path}/{self.day}"): + os.makedirs(f"{save_path}/{self.day}", exist_ok=True) except ValueError as e: - print(e) + sys.exit(e) except Exception as e: - print(e) + sys.exit(e) for i in tqdm(range(self.n_particles), desc="Initializing velocity"): p = self.particles[i] local_score = p.get_score(x, y, renewal=renewal) - + particle_sum += local_score[1] if renewal == "acc": if local_score[1] > self.g_best_score[0]: self.g_best_score[0] = local_score[1] @@ -301,7 +307,7 @@ class Optimizer: if log == 1: with open( - f"./{save_path}/{self.day}_{self.n_particles}_{epochs}_{self.c0}_{self.c1}_{self.w_min}_{renewal}.csv", + f"./{save_path}/{self.day}/{self.n_particles}_{epochs}_{self.c0}_{self.c1}_{self.w_min}_{renewal}.csv", "a", ) as f: f.write(f"{local_score[0]}, {local_score[1]}") @@ -316,14 +322,15 @@ class Optimizer: tf.summary.scalar("accuracy", local_score[1], step=0) del local_score - gc.collect() - tf.keras.backend.reset_uids() - tf.keras.backend.clear_session() + # gc.collect() + # tf.keras.backend.reset_uids() + # tf.keras.backend.clear_session() print( f"initial g_best_score : {self.g_best_score[0] if self.renewal == 'acc' else self.g_best_score[1]}" ) try: + epoch_sum = 0 epochs_pbar = tqdm( range(epochs), desc=f"best {self.g_best_score[0]:.4f}|{self.g_best_score[1]:.4f}", @@ -332,8 +339,11 @@ class Optimizer: position=0, ) for epoch in epochs_pbar: + particle_avg = particle_sum / self.n_particles # x_j + particle_sum = 0 max_score = 0 min_loss = np.inf + # epoch_particle_sum = 0 part_pbar = tqdm( range(len(self.particles)), desc=f"acc : {max_score:.4f} loss : {min_loss:.4f}", @@ -347,20 +357,22 @@ class Optimizer: f"acc : {max_score:.4f} loss : {min_loss:.4f}" ) + g_best = self.g_best + if dispersion: - ts = self.c0 + np.random.rand() * (self.c1 - self.c0) + ts = self.particle_min + np.random.rand() * ( + self.particle_max - self.particle_min + ) g_, g_sh, g_len = self._encode(self.g_best) - decrement = (epochs - (epoch) + 1) / epochs + decrement = (epochs - epoch + 1) / epochs g_ = (1 - decrement) * g_ + decrement * ts self.g_best_ = self._decode(g_, g_sh, g_len) g_best = self.g_best_ - else: - g_best = self.g_best if empirical_balance: if np.random.rand() < np.exp(-(epoch) / epochs): - w_p_ = self.f(x, y, self.particles[i].get_best_weights()) - w_g_ = self.f(x, y, self.g_best) + w_p_ = self._f(x, y, self.particles[i].get_best_weights()) + w_g_ = self._f(x, y, self.g_best) w_p = w_p_ / (w_p_ + w_g_) w_g = w_p_ / (w_p_ + w_g_) @@ -371,13 +383,35 @@ class Optimizer: p_b = self.particles[i].get_best_score() g_a = self.avg_score l_b = p_b - g_a - l_b = np.sqrt(np.power(l_b, 2)) - p_ = ( + sigma_post = np.sqrt(np.power(l_b, 2)) + sigma_pre = ( 1 - / (self.n_particles * np.linalg.norm(self.c1 - self.c0)) - * l_b + / ( + self.n_particles + * np.linalg.norm( + self.particle_max - self.particle_min + ) + ) + * sigma_post ) - p_ = np.exp(-1 * p_) + p_ = np.exp(-1 * sigma_pre * sigma_post) + + # p_ = ( + # 1 + # / (self.n_particles * np.linalg.norm(self.particle_max - self.particle_min)) + # * np.exp( + # -np.power(l_b, 2) / (2 * np.power(self.sigma, 2)) + # ) + # ) + # g_ = ( + # 1 + # / np.linalg.norm(self.c1 - self.c0) + # * np.exp( + # -np.power(l_b, 2) / (2 * np.power(self.sigma, 2)) + # ) + # ) + # w_p = p_ / (p_ + g_) + # w_g = g_ / (p_ + g_) w_p = p_ w_g = 1 - p_ @@ -397,6 +431,7 @@ class Optimizer: w_g, renewal=renewal, ) + epoch_sum += np.power(score[1] - particle_avg, 2) else: score = self.particles[i].step( @@ -457,10 +492,11 @@ class Optimizer: epochs_pbar.set_description( f"best {self.g_best_score[0]:.4f} | {self.g_best_score[1]:.4f}" ) + particle_sum += score[1] if log == 1: with open( - f"./{save_path}/{self.day}_{self.n_particles}_{epochs}_{self.c0}_{self.c1}_{self.w_min}_{renewal}.csv", + f"./{save_path}/{self.day}/{self.n_particles}_{epochs}_{self.c0}_{self.c1}_{self.w_min}_{renewal}.csv", "a", ) as f: f.write(f"{score[0]}, {score[1]}") @@ -468,9 +504,6 @@ class Optimizer: f.write(", ") else: f.write("\n") - # gc.collect() - # tf.keras.backend.reset_uids() - # tf.keras.backend.clear_session() part_pbar.refresh() if check_point is not None: @@ -536,7 +569,7 @@ class Optimizer: path (str, optional): 저장 위치. Defaults to "./result". """ json_save = { - "name": f"{self.day}_{self.n_particles}_{self.c0}_{self.c1}_{self.w_min}.h5", + "name": f"{self.day}/{self.n_particles}_{self.c0}_{self.c1}_{self.w_min}.h5", "n_particles": self.n_particles, "score": self.g_best_score, "c0": self.c0, diff --git a/pso/particle.py b/pso/particle.py index 2be297f..afef9fd 100644 --- a/pso/particle.py +++ b/pso/particle.py @@ -2,6 +2,7 @@ import numpy as np from tensorflow import keras + class Particle: """ Particle Swarm Optimization의 Particle을 구현한 클래스 @@ -112,8 +113,6 @@ class Particle: self.best_score = score[1] self.best_weights = self.model.get_weights() elif renewal == "loss": - if score[0] == "nan": - score[0] = np.inf if score[0] < self.best_score: self.best_score = score[0] self.best_weights = self.model.get_weights() @@ -134,11 +133,11 @@ class Particle: encode_v, v_sh, v_len = self._encode(weights=self.velocities) encode_p, p_sh, p_len = self._encode(weights=self.best_weights) encode_g, g_sh, g_len = self._encode(weights=g_best) - r0 = np.random.rand() - r1 = np.random.rand() encode_before, before_sh, before_len = self._encode(weights=self.before_best) + r_0 = np.random.rand() + r_1 = np.random.rand() - if (encode_before != encode_g).all(): + if not np.array_equal(encode_before, encode_g, equal_nan=True): self.before_w = w * 0.6 w = w + self.before_w else: @@ -148,14 +147,14 @@ class Particle: if self.negative: new_v = ( w * encode_v - + -1 * local_rate * r0 * (encode_p - encode_w) - + -1 * global_rate * r1 * (encode_g - encode_w) + + local_rate * r_0 * (encode_p - encode_w) + + -1 * global_rate * r_1 * (encode_g - encode_w) ) else: new_v = ( w * encode_v - + local_rate * r0 * (encode_p - encode_w) - + global_rate * r1 * (encode_g - encode_w) + + local_rate * r_0 * (encode_p - encode_w) + + global_rate * r_1 * (encode_g - encode_w) ) if np.random.rand() < self.mutation: @@ -169,7 +168,7 @@ class Particle: del encode_p, p_sh, p_len del encode_g, g_sh, g_len del encode_before, before_sh, before_len - del r0, r1 + del r_0, r_1 def _update_velocity_w(self, local_rate, global_rate, w, w_p, w_g, g_best): """ @@ -188,20 +187,27 @@ class Particle: encode_v, v_sh, v_len = self._encode(weights=self.velocities) encode_p, p_sh, p_len = self._encode(weights=self.best_weights) encode_g, g_sh, g_len = self._encode(weights=g_best) - r0 = np.random.rand() - r1 = np.random.rand() + encode_before, before_sh, before_len = self._encode(weights=self.before_best) + r_0 = np.random.rand() + r_1 = np.random.rand() + if not np.array_equal(encode_before, encode_g, equal_nan=True): + self.before_w = w * 0.6 + w = w + self.before_w + else: + self.before_w *= 0.75 + w = w + self.before_w if self.negative: new_v = ( w * encode_v - + -1 * local_rate * r0 * (w_p * encode_p - encode_w) - + -1 * global_rate * r1 * (w_g * encode_g - encode_w) + + local_rate * r_0 * (w_p * encode_p - encode_w) + + -1 * global_rate * r_1 * (w_g * encode_g - encode_w) ) else: new_v = ( w * encode_v - + local_rate * r0 * (w_p * encode_p - encode_w) - + global_rate * r1 * (w_g * encode_g - encode_w) + + local_rate * r_0 * (w_p * encode_p - encode_w) + + global_rate * r_1 * (w_g * encode_g - encode_w) ) if np.random.rand() < self.mutation: @@ -214,7 +220,8 @@ class Particle: del encode_v, v_sh, v_len del encode_p, p_sh, p_len del encode_g, g_sh, g_len - del r0, r1 + del encode_before, before_sh, before_len + del r_0, r_1 def _update_weights(self): """ diff --git a/test01.py b/test01.py new file mode 100644 index 0000000..6c10d3e --- /dev/null +++ b/test01.py @@ -0,0 +1,11 @@ +# 반복문을 사용해서 자동 생성하는 python 코드 + + +def pibonachi(n): + if n <= 1: + return n + else: + return pibonachi(n - 1) + pibonachi(n - 2) + + +print(pibonachi(10)) diff --git a/xor.py b/xor.py index 302fb4f..60ef49f 100644 --- a/xor.py +++ b/xor.py @@ -11,7 +11,7 @@ from tensorflow.keras import layers from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential -from pso import Optimizer +from pso import optimizer def get_data(): @@ -47,10 +47,10 @@ loss = [ "mean_absolute_percentage_error", ] -pso_xor = Optimizer( +pso_xor = optimizer( model, loss=loss[0], - n_particles=50, + n_particles=100, c0=0.35, c1=0.8, w_min=0.6, @@ -66,6 +66,7 @@ best_score = pso_xor.fit( epochs=200, save_info=True, log=2, + log_name="xor", save_path="./result/xor", renewal="acc", check_point=25,