Spaces:
Sleeping
Sleeping
KJMAN678
commited on
Commit
·
3cc63f3
1
Parent(s):
4e20d4d
コードの修正, requirements.txt にmatplotlibを追加
Browse files- README.md +48 -6
- requirements.txt +1 -0
- simulation.py +24 -95
- stable_diffusion_cpu.ipynb +0 -0
README.md
CHANGED
@@ -33,7 +33,7 @@
|
|
33 |
|
34 |
### How to Execute / 実行方法
|
35 |
|
36 |
-
- Verify execution with Python 3.7.13
|
37 |
|
38 |
- On Colab
|
39 |
- Open [StableDiffusionSample.ipynb on Colab](https://colab.research.google.com/drive/1Uaqmq3ibMmEwepnn4OWHf2TVboUVa14O?usp=sharing)
|
@@ -41,17 +41,35 @@
|
|
41 |
|
42 |
- On Local
|
43 |
- Install requirements.txt library in a virtual environment, etc.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
- Launch notebook StableDiffusionByCpu.ipynb.
|
45 |
|
46 |
- Common
|
47 |
-
- Create a Hugging Face account.
|
48 |
-
- Create an access token in Hugging Face Setting.
|
|
|
49 |
- Allow the use of the model you want to use (e.g. CompVis/stable-diffusion-v1-4), referring to the explanation on the official site.
|
50 |
- Run a Colab or Local notebook, enter the Hugging Face token into the notebook, login and run the notebook.
|
|
|
51 |
|
52 |
---------------------------------------------
|
53 |
|
54 |
-
- Python 3.7.13 で実行を確認
|
55 |
|
56 |
- グーグルコラボ
|
57 |
- [StableDiffusionSample.ipynb on Colab](https://colab.research.google.com/drive/1Uaqmq3ibMmEwepnn4OWHf2TVboUVa14O?usp=sharing)を開く
|
@@ -59,13 +77,31 @@
|
|
59 |
|
60 |
- ローカル環境
|
61 |
- 仮想環境などに requirements.txt のライブラリをインストールする
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
- 共通
|
65 |
- [Hugging Face](https://huggingface.co/)のアカウントを作成する
|
66 |
- [Hugging Face の Setting](https://huggingface.co/settings/tokens)でアクセストークンを作成する
|
|
|
67 |
- [公式サイトの解説](https://huggingface.co/docs/hub/security-tokens)を参考に、使用するモデル(例: CompVis/stable-diffusion-v1-4)の使用を許可する
|
68 |
- Colab または Local のノートブックを実行し、Hugging Face のトークンをノートブックに入力しログインしてノートブックを実行する。
|
|
|
69 |
|
70 |
### File Organization / ファイル構成
|
71 |
|
@@ -77,4 +113,10 @@
|
|
77 |
- 遺伝的アルゴリズムによるシミュレーションを行っているファイル。Colab、ローカルいずれの場合も必要。
|
78 |
- sample_output_images
|
79 |
- Folder containing the Output image described above.
|
80 |
-
- 上述のOutput画像が入ったフォルダ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
### How to Execute / 実行方法
|
35 |
|
36 |
+
- Verify execution with M1 Mac, Python 3.7.13
|
37 |
|
38 |
- On Colab
|
39 |
- Open [StableDiffusionSample.ipynb on Colab](https://colab.research.google.com/drive/1Uaqmq3ibMmEwepnn4OWHf2TVboUVa14O?usp=sharing)
|
|
|
41 |
|
42 |
- On Local
|
43 |
- Install requirements.txt library in a virtual environment, etc.
|
44 |
+
|
45 |
+
### Command Example (Mac)
|
46 |
+
```
|
47 |
+
### Create a virtual environment
|
48 |
+
python -m venv .venv
|
49 |
+
|
50 |
+
## Activate your virtual environment.
|
51 |
+
source .venv/bin/activate
|
52 |
+
|
53 |
+
## Upgrade pip
|
54 |
+
python -m pip install --upgrade pip
|
55 |
+
|
56 |
+
## Install library
|
57 |
+
pip install -r requirements.txt
|
58 |
+
```
|
59 |
+
|
60 |
- Launch notebook StableDiffusionByCpu.ipynb.
|
61 |
|
62 |
- Common
|
63 |
+
- Create a [Hugging Face](https://huggingface.co/) account.
|
64 |
+
- Create an access token in [Hugging Face Setting](https://huggingface.co/settings/tokens).
|
65 |
+

|
66 |
- Allow the use of the model you want to use (e.g. CompVis/stable-diffusion-v1-4), referring to the explanation on the official site.
|
67 |
- Run a Colab or Local notebook, enter the Hugging Face token into the notebook, login and run the notebook.
|
68 |
+

|
69 |
|
70 |
---------------------------------------------
|
71 |
|
72 |
+
- M1 Mac, Python 3.7.13 で実行を確認
|
73 |
|
74 |
- グーグルコラボ
|
75 |
- [StableDiffusionSample.ipynb on Colab](https://colab.research.google.com/drive/1Uaqmq3ibMmEwepnn4OWHf2TVboUVa14O?usp=sharing)を開く
|
|
|
77 |
|
78 |
- ローカル環境
|
79 |
- 仮想環境などに requirements.txt のライブラリをインストールする
|
80 |
+
|
81 |
+
### コマンド例(Mac)
|
82 |
+
```
|
83 |
+
### 仮想環境の作成
|
84 |
+
python -m venv .venv
|
85 |
+
|
86 |
+
## 仮想環境のアクティベート
|
87 |
+
source .venv/bin/activate
|
88 |
+
|
89 |
+
## pip のアップグレード
|
90 |
+
python -m pip install --upgrade pip
|
91 |
+
|
92 |
+
## ライブラリのインストール
|
93 |
+
pip install -r requirements.txt
|
94 |
+
```
|
95 |
+
|
96 |
+
- stable_diffusion_cpu.ipynb を立ち上げる
|
97 |
|
98 |
- 共通
|
99 |
- [Hugging Face](https://huggingface.co/)のアカウントを作成する
|
100 |
- [Hugging Face の Setting](https://huggingface.co/settings/tokens)でアクセストークンを作成する
|
101 |
+

|
102 |
- [公式サイトの解説](https://huggingface.co/docs/hub/security-tokens)を参考に、使用するモデル(例: CompVis/stable-diffusion-v1-4)の使用を許可する
|
103 |
- Colab または Local のノートブックを実行し、Hugging Face のトークンをノートブックに入力しログインしてノートブックを実行する。
|
104 |
+

|
105 |
|
106 |
### File Organization / ファイル構成
|
107 |
|
|
|
113 |
- 遺伝的アルゴリズムによるシミュレーションを行っているファイル。Colab、ローカルいずれの場合も必要。
|
114 |
- sample_output_images
|
115 |
- Folder containing the Output image described above.
|
116 |
+
- 上述のOutput画像が入ったフォルダ
|
117 |
+
|
118 |
+
|
119 |
+
### Reference site / 参考サイト
|
120 |
+
|
121 |
+
- [【python】遺伝的アルゴリズム(Genetic Algorithm)を実装してみる](https://mori-memo.hateblo.jp/entry/2022/06/16/232644)
|
122 |
+
- [CompVis/stable-diffusionの環境をApple Siliconで構築する](https://zenn.dev/laiso/articles/7af434269ffa1b)
|
requirements.txt
CHANGED
@@ -4,4 +4,5 @@ ipywidgets==7.7.2
|
|
4 |
pandas==1.3.5
|
5 |
ftfy==6.1.1
|
6 |
spacy==3.4.1
|
|
|
7 |
notebook==6.4.12
|
|
|
4 |
pandas==1.3.5
|
5 |
ftfy==6.1.1
|
6 |
spacy==3.4.1
|
7 |
+
matplotlib==3.5.3
|
8 |
notebook==6.4.12
|
simulation.py
CHANGED
@@ -1,28 +1,9 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""simulation.ipynb
|
3 |
-
|
4 |
-
Automatically generated by Colaboratory.
|
5 |
-
|
6 |
-
Original file is located at
|
7 |
-
https://colab.research.google.com/drive/1ZVm7p9Kb39Br5GUk1qVby8sG7YmlXLJX
|
8 |
-
|
9 |
-
- [遺伝アルゴリズム 参考記事](https://mori-memo.hateblo.jp/entry/2022/06/16/232644#%E5%88%9D%E6%9C%9F%E4%B8%96%E4%BB%A3%E3%81%AE%E4%BD%9C%E6%88%90)
|
10 |
-
- [バックアップ](https://colab.research.google.com/drive/1CfA0nBjBrrTS3lj0H5-TbOTTD0JdSCqW#scrollTo=rLmsKrtg1NPE)
|
11 |
-
- [【NASAより】火星の気温](https://mars.nasa.gov/files/mep/facts/Temperature-Mars-Facts.jpg)
|
12 |
-
"""
|
13 |
-
|
14 |
-
import numpy as np
|
15 |
-
import matplotlib.pyplot as plt
|
16 |
import random
|
17 |
from typing import Tuple, Dict, List
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
3. (済) 各パラメーターのスコアの推移を表示
|
23 |
-
4. スコアがintデータから途中でfloat型になってしまう -> スコアは修正済み、遺伝子の中の数が変
|
24 |
-
5. パラメーター調整 -> 気温や餌の量のしきい値、共同体の規模や世代数など
|
25 |
-
"""
|
26 |
|
27 |
class Individual:
|
28 |
'''各個体のクラス
|
@@ -122,7 +103,9 @@ def create_generation(POPURATIONS, GENOMS_SIZE):
|
|
122 |
generation[individual] = 0
|
123 |
return generation
|
124 |
|
125 |
-
def select_tournament(
|
|
|
|
|
126 |
|
127 |
"""
|
128 |
選択の関数(トーナメント方式)。すべてのgenerationから3つ選び、強い(scoreが最も高い)genomを1つ選ぶ。これをgenerationのサイズだけ繰り返す
|
@@ -133,17 +116,17 @@ def select_tournament(generation_: List[Tuple[Individual, int]]) -> List[Tuple[I
|
|
133 |
List[Tuple[Individual, int]] : トーナメント戦で生き残ったゲノム1つ
|
134 |
"""
|
135 |
|
136 |
-
|
137 |
|
138 |
-
for i in range(len(
|
139 |
|
140 |
# 最もスコアのよいgeneration を採用
|
141 |
tournament = random.sample(generation_, TOUNAMENT_NUM)
|
142 |
max_genom = max(tournament, key=lambda x: x[1])
|
143 |
|
144 |
-
|
145 |
|
146 |
-
return
|
147 |
|
148 |
def cross_two_point_copy(child1, child2):
|
149 |
'''二点交叉'''
|
@@ -181,7 +164,7 @@ def cross_two_point_copy(child1, child2):
|
|
181 |
|
182 |
return child1, child2
|
183 |
|
184 |
-
def crossover(selected):
|
185 |
'''交叉の関数'''
|
186 |
children = []
|
187 |
if POPURATIONS % 2:
|
@@ -194,19 +177,15 @@ def crossover(selected):
|
|
194 |
children = children[:POPURATIONS]
|
195 |
return children
|
196 |
|
197 |
-
def mutate(children):
|
198 |
-
for child in children:
|
199 |
-
if np.random.rand() < MUTATION_PB:
|
200 |
-
child.mutate()
|
201 |
-
return children
|
202 |
|
203 |
-
def mutate(children):
|
204 |
|
205 |
tmp_children = []
|
206 |
|
207 |
for child in children:
|
208 |
individual, score = child[0], child[1]
|
209 |
-
|
|
|
210 |
|
211 |
tmp_children.append((individual, score))
|
212 |
|
@@ -220,6 +199,10 @@ def reset_generation_score(generation_):
|
|
220 |
return generation_
|
221 |
|
222 |
def scoring(generation_, temperature, food_volume):
|
|
|
|
|
|
|
|
|
223 |
|
224 |
generation_ = reset_generation_score(generation_)
|
225 |
|
@@ -280,7 +263,7 @@ def scoring(generation_, temperature, food_volume):
|
|
280 |
|
281 |
return generation_
|
282 |
|
283 |
-
def ga_solve(generation):
|
284 |
'''遺伝的アルゴリズムのソルバー
|
285 |
return: 最終世代の最高適応値の個体、最低適応値の個体'''
|
286 |
|
@@ -307,7 +290,7 @@ def ga_solve(generation):
|
|
307 |
# Dict だと Key の重複ができないため
|
308 |
generation_ = [(individual, score) for individual, score in generation.items()]
|
309 |
|
310 |
-
for i in range(
|
311 |
|
312 |
temperature = random_temperature()
|
313 |
temperature_transition.append(temperature)
|
@@ -331,13 +314,13 @@ def ga_solve(generation):
|
|
331 |
# )
|
332 |
|
333 |
# --- Step2. Selection (Roulette)
|
334 |
-
selected_genoms = select_tournament(generation_)
|
335 |
|
336 |
# --- Step3. Crossover (two_point_copy)
|
337 |
-
children = crossover(selected_genoms)
|
338 |
|
339 |
# --- Step4. Mutation
|
340 |
-
generation_ = mutate(children)
|
341 |
|
342 |
for parameter, genom in best_individual_score[0].all_genoms.items():
|
343 |
parameter_transiton[parameter].append(sum(genom))
|
@@ -382,58 +365,4 @@ def get_word_for_image_generate(word_dict, best, index):
|
|
382 |
|
383 |
# 最終的な I/F 補足: スペース区切りの文字列 を渡す, 英語もありうる
|
384 |
word = " ".join(word_list)
|
385 |
-
return word
|
386 |
-
|
387 |
-
"""### 実行"""
|
388 |
-
|
389 |
-
# シード値の固定
|
390 |
-
SEED = 42
|
391 |
-
np.random.seed(seed=SEED)
|
392 |
-
random.seed(SEED)
|
393 |
-
|
394 |
-
# パラメーター
|
395 |
-
POPURATIONS = 200
|
396 |
-
GENOMS_SIZE = 4 # 遺伝配列 0, 1 のどちらかを要素とした配列のサイズ
|
397 |
-
GENERATIONS = 1000 # 世代数
|
398 |
-
CROSSOVER_PB = 0.5 # cross over(交差) する確率
|
399 |
-
MUTATION_PB = 0.7 # mutation(突然変異)する確率
|
400 |
-
TOUNAMENT_NUM = 10 # トーナメント方式で競わせる数
|
401 |
-
MAX_NUM = 4 # fitness の最大値
|
402 |
-
|
403 |
-
THREASHOLD_TEMPRETURE = 5
|
404 |
-
THREASHOLD_FOOD_VOLUME = 1500
|
405 |
-
|
406 |
-
# 渡すデータの加工イメージ
|
407 |
-
# dict 型 {項目(key): 画像生成プログラムに与えるキーワード{value}}
|
408 |
-
word_dict = {
|
409 |
-
"body_size": ["Very small", "Small", "Ordinary size", "Big", "Giant"],
|
410 |
-
"body_hair": ["Very Skinny", "Skinny", "Ordinary Skin", "Furry", "Very Furry"],
|
411 |
-
"herd_num": ["Lone", "Pair", "Eight", "Many", "Too Many"],
|
412 |
-
"eating": ["Very Herbivorous", "Herbivorous", "Omnivorous", "Carnivorous","Very Carnivorous"],
|
413 |
-
"body_color": ["Lightest", "Lighter", "Ordinary Tone", "Darker", "Darkest"],
|
414 |
-
"ferocity": ["Very Gentle", "Gentle", "Ordinary", "Ferocious", "Very Ferocious"],
|
415 |
-
}
|
416 |
-
|
417 |
-
# create first genetarion
|
418 |
-
generation = create_generation(POPURATIONS, GENOMS_SIZE)
|
419 |
-
|
420 |
-
# アルゴリズムの実行
|
421 |
-
best, worst = ga_solve(generation)
|
422 |
-
|
423 |
-
# 抽出する世代
|
424 |
-
first_generation = 0
|
425 |
-
midle_generation = len(best) // 2
|
426 |
-
last_generation = -1
|
427 |
-
|
428 |
-
first_generation_word = get_word_for_image_generate(word_dict, best, first_generation) + " alien from Mars"
|
429 |
-
midle_generation_word = get_word_for_image_generate(word_dict, best, midle_generation) + " alien from Mars"
|
430 |
-
last_generation_word = get_word_for_image_generate(word_dict, best, last_generation) + " alien from Mars"
|
431 |
-
|
432 |
-
# 抽出する世代のワードを出力
|
433 |
-
print()
|
434 |
-
print(
|
435 |
-
"最初の世代:", first_generation_word, "\n",
|
436 |
-
f"中間の{midle_generation}世代目:", midle_generation_word, "\n",
|
437 |
-
f"最後の{GENERATIONS}世代目:", last_generation_word, "\n",
|
438 |
-
)
|
439 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import random
|
2 |
from typing import Tuple, Dict, List
|
3 |
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import numpy as np
|
6 |
+
|
|
|
|
|
|
|
|
|
7 |
|
8 |
class Individual:
|
9 |
'''各個体のクラス
|
|
|
103 |
generation[individual] = 0
|
104 |
return generation
|
105 |
|
106 |
+
def select_tournament(
|
107 |
+
generation_: List[Tuple[Individual, int]], TOUNAMENT_NUM
|
108 |
+
) -> List[Tuple[Individual, int]]:
|
109 |
|
110 |
"""
|
111 |
選択の関数(トーナメント方式)。すべてのgenerationから3つ選び、強い(scoreが最も高い)genomを1つ選ぶ。これをgenerationのサイズだけ繰り返す
|
|
|
116 |
List[Tuple[Individual, int]] : トーナメント戦で生き残ったゲノム1つ
|
117 |
"""
|
118 |
|
119 |
+
selected_genoms = []
|
120 |
|
121 |
+
for i in range(len(generation_)):
|
122 |
|
123 |
# 最もスコアのよいgeneration を採用
|
124 |
tournament = random.sample(generation_, TOUNAMENT_NUM)
|
125 |
max_genom = max(tournament, key=lambda x: x[1])
|
126 |
|
127 |
+
selected_genoms.append(max_genom)
|
128 |
|
129 |
+
return selected_genoms
|
130 |
|
131 |
def cross_two_point_copy(child1, child2):
|
132 |
'''二点交叉'''
|
|
|
164 |
|
165 |
return child1, child2
|
166 |
|
167 |
+
def crossover(selected, POPURATIONS, CROSSOVER_PB):
|
168 |
'''交叉の関数'''
|
169 |
children = []
|
170 |
if POPURATIONS % 2:
|
|
|
177 |
children = children[:POPURATIONS]
|
178 |
return children
|
179 |
|
|
|
|
|
|
|
|
|
|
|
180 |
|
181 |
+
def mutate(children, MUTATION_PB):
|
182 |
|
183 |
tmp_children = []
|
184 |
|
185 |
for child in children:
|
186 |
individual, score = child[0], child[1]
|
187 |
+
if np.random.rand() < MUTATION_PB:
|
188 |
+
individual.mutate()
|
189 |
|
190 |
tmp_children.append((individual, score))
|
191 |
|
|
|
199 |
return generation_
|
200 |
|
201 |
def scoring(generation_, temperature, food_volume):
|
202 |
+
|
203 |
+
MAX_NUM = 4 # fitness の最大値
|
204 |
+
THREASHOLD_TEMPRETURE = 10 # score の判定に用いる気温のしきい値
|
205 |
+
THREASHOLD_FOOD_VOLUME = 3000 # score の判定に用いる食料のしきい値
|
206 |
|
207 |
generation_ = reset_generation_score(generation_)
|
208 |
|
|
|
263 |
|
264 |
return generation_
|
265 |
|
266 |
+
def ga_solve(generation, NUM_GENERATION, POPURATIONS, TOUNAMENT_NUM, CROSSOVER_PB, MUTATION_PB):
|
267 |
'''遺伝的アルゴリズムのソルバー
|
268 |
return: 最終世代の最高適応値の個体、最低適応値の個体'''
|
269 |
|
|
|
290 |
# Dict だと Key の重複ができないため
|
291 |
generation_ = [(individual, score) for individual, score in generation.items()]
|
292 |
|
293 |
+
for i in range(NUM_GENERATION):
|
294 |
|
295 |
temperature = random_temperature()
|
296 |
temperature_transition.append(temperature)
|
|
|
314 |
# )
|
315 |
|
316 |
# --- Step2. Selection (Roulette)
|
317 |
+
selected_genoms = select_tournament(generation_, TOUNAMENT_NUM)
|
318 |
|
319 |
# --- Step3. Crossover (two_point_copy)
|
320 |
+
children = crossover(selected_genoms, POPURATIONS, CROSSOVER_PB)
|
321 |
|
322 |
# --- Step4. Mutation
|
323 |
+
generation_ = mutate(children, MUTATION_PB)
|
324 |
|
325 |
for parameter, genom in best_individual_score[0].all_genoms.items():
|
326 |
parameter_transiton[parameter].append(sum(genom))
|
|
|
365 |
|
366 |
# 最終的な I/F 補足: スペース区切りの文字列 を渡す, 英語もありうる
|
367 |
word = " ".join(word_list)
|
368 |
+
return word
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
stable_diffusion_cpu.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|