quilt code

[AI] tensorflow (3) 본문

daily/AI

[AI] tensorflow (3)

김뱅쇼 2023. 4. 22. 14:34

가위바위보 예제

 

1. day15


1. gawi_mnist


user가 무조건 이기는 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import tensorflow as tf
import numpy as np
 
 
 
x_train = [
            [100],  #가위
            [010],  #바위
            [001],  #보
]
 
y_train = [201]
 
 
x_test = [
            [100]  #가위
        
]
 
x_train_np = np.array(x_train, dtype='f')   #모델의 입맛에 맞추기 위해 실수로 바꿈 / 배열은 모델안에 들어갈 수 없어서 numpy로 바꿔줌
y_train_np = np.array(y_train, dtype='f')
x_test_np = np.array(x_test, dtype='f')
 
#모델 구성
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(3,)),
    tf.keras.layers.Dense(25, activation=tf.nn.relu),
    tf.keras.layers.Dense(25, activation=tf.nn.relu),
    tf.keras.layers.Dense(3, activation=tf.nn.softmax)
])
#4. 모델 컴파일
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
#모델 훈련
model.fit(x_train, y_train, epochs=15)
 
model.save("gawi.h5")
 
predict = model.predict(x_test_np)
idx_pred = np.argmax(predict[0])
 
print(predict)
cs


x_train = [
            [1, 0, 0],  #가위
            [0, 1, 0],  #바위
            [0, 0, 1],  #보
]

y_train = [201] :  x_train이 가위 [1,0,0]일때 y_train은 2로 출력 (why 2? 가위-보여야하니까 보[0 0 1]의 argmax값 2)
                               나머지는 그림 참고 




 


2. gawi_ai



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
import tensorflow as tf
import keras
 
mine=""
com = ""
result = ""   #선언부 
 
mine = input("가위/바위/보를 입력하세요.")
 
x_test = []
 
if mine == "가위":
    x_test.append([100]) 
elif mine == "바위":
    x_test.append([010])
else:
    x_test.append([001])
    
x_test_np = np.array(x_test)
model = keras.models.load_model("gawi.h5")
predict = model.predict(x_test_np)
 
inx_gw = np.argmax(predict[0])
 
if inx_gw == 0:
    com = "가위"
elif inx_gw == 1:
    com = "바위"                                    
else:
    com = "보"
   
if com == "가위" and mine == "가위" : result = "비김"
if com == "가위" and mine == "바위" : result = "승리"
if com == "가위" and mine == "보" : result = "패배"
 
if com == "바위" and mine == "가위" : result = "패배"
if com == "바위" and mine == "바위" : result = "비김"
if com == "바위" and mine == "보" : result = "승리"
 
if com == "보" and mine == "가위" : result = "승리"
if com == "보" and mine == "바위" : result = "패배"
if com == "보" and mine == "보" : result = "비김"
 
print("나:",mine)
print("컴:",com)
print("결과:",result)
cs
 

 

 

2. day16

 


1. gawi_mnist



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import tensorflow as tf
import numpy as np
 
 
 
x_train = [
            [0],  #가위
            [0.5],  #바위
            [1],  #보
]
 
y_train = [201#이기는 게임 gawi_ai
# y_train = [0, 1, 2]
 
 
x_test = [
            [0]  #가위
        
]
 
x_train_np = np.array(x_train, dtype='f')   #모델의 입맛에 맞추기 위해 실수로 바꿈 / 배열은 모델안에 들어갈 수 없어서 numpy로 바꿔줌
y_train_np = np.array(y_train, dtype='f')
x_test_np = np.array(x_test, dtype='f')
 
#모델 구성
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(1,)),
    tf.keras.layers.Dense(25, activation=tf.nn.relu),
    tf.keras.layers.Dense(25, activation=tf.nn.relu),
    tf.keras.layers.Dense(3, activation=tf.nn.softmax)
])
#4. 모델 컴파일
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
#모델 훈련
model.fit(x_train, y_train, epochs=214)
 
model.save("gawi.h5")
 
predict = model.predict(x_test_np)
idx_pred = np.argmax(predict[0])
 
print(predict)
cs

x_train = [
            [0],  #가위
            [0.5],  #바위
            [1],  #보
]





2. gawi_ai



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
import tensorflow as tf
import keras
 
mine=""
com = ""
result = ""   #선언부 
 
mine = input("가위/바위/보를 입력하세요.")
 
x_test = []
 
if mine == "가위":
    x_test.append([0]) 
elif mine == "바위":
    x_test.append([0.5])
else:
    x_test.append([1])
    
x_test_np = np.array(x_test)
model = keras.models.load_model("gawi.h5")
predict = model.predict(x_test_np)
 
inx_gw = np.argmax(predict[0])
 
if inx_gw == 0:
    com = "가위"
elif inx_gw == 1:
    com = "바위"                                    
else:
    com = "보"
   
if com == "가위" and mine == "가위" : result = "비김"
if com == "가위" and mine == "바위" : result = "승리"
if com == "가위" and mine == "보" : result = "패배"
 
if com == "바위" and mine == "가위" : result = "패배"
if com == "바위" and mine == "바위" : result = "비김"
if com == "바위" and mine == "보" : result = "승리"
 
if com == "보" and mine == "가위" : result = "승리"
if com == "보" and mine == "바위" : result = "패배"
if com == "보" and mine == "보" : result = "비김"
 
print("나:",mine)
print("컴:",com)
print("결과:",result)
cs
 

 

 


3. mygui09_ai


무조건 비기는 가위바위보


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
import numpy as np
import tensorflow as tf
import keras
from day16.gawi_aao import AaoGawi
 
form_class = uic.loadUiType("mygui09.ui")[0]
 
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
 
        self.ag = AaoGawi()
        self.ag.load()
        self.setupUi(self)
        self.pb.clicked.connect(self.myclick)
        self.leMine.returnPressed.connect(self.myclick) #엔터칠때 클릭이랑 같은 기능
        
    
    def myclick(self):
        
        mine=""
        com = ""
        result = "" 
        
        mine = self.leMine.text()
        # com = self.leCom.text()
        # result = self.leResult.text()
        
        x_test = []
    
        if mine == "가위":
            x_test.append([0]) 
        elif mine == "바위":
            x_test.append([0.5])
        else:
            x_test.append([1])
            
        x_test_np = np.array(x_test)
        predict = self.ag.model.predict(x_test_np)
        
        inx_gw = np.argmax(predict[0])
        
        if inx_gw == 0:
            com = "가위"
        elif inx_gw == 1:
            com = "바위"                                    
        else:
            com = "보"
            
        if com == "가위" and mine == "가위" : result = "비김"
        if com == "가위" and mine == "바위" : result = "승리"
        if com == "가위" and mine == "보" : result = "패배"
 
        if com == "바위" and mine == "가위" : result = "패배"
        if com == "바위" and mine == "바위" : result = "비김"
        if com == "바위" and mine == "보" : result = "승리"
 
        if com == "보" and mine == "가위" : result = "승리"
        if com == "보" and mine == "바위" : result = "패배"
        if com == "보" and mine == "보" : result = "비김"
        
       
        self.leCom.setText(com)
        self.leResult.setText(result)
        
       
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()
cs



 


4. gawi_aao
 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import tensorflow as tf
import numpy as np
import keras
 
 
 
#전역으로 빼기
class AaoGawi:
    def __init__(self):
        self.model = None
    
    def load(self):
        self.model = keras.models.load_model("gawi.h5")
        
    def run_makeh5(self):
 
 
        x_train = [
                    [0],  #가위
                    [0.5],  #바위
                    [1],  #보
        ]
        
        # y_train = [2, 0, 1] #이기는 게임 gawi_ai
        y_train = [012]
        
        
        x_test = [
                    [0]  #가위
                
        ]
        
        x_train_np = np.array(x_train, dtype='f')   #모델의 입맛에 맞추기 위해 실수로 바꿈 / 배열은 모델안에 들어갈 수 없어서 numpy로 바꿔줌
        y_train_np = np.array(y_train, dtype='f')
        x_test_np = np.array(x_test, dtype='f')
 
        #모델 구성
        self.model = tf.keras.models.Sequential([
            tf.keras.layers.Flatten(input_shape=(1,)),
            tf.keras.layers.Dense(25, activation=tf.nn.relu),
            tf.keras.layers.Dense(25, activation=tf.nn.relu), #히든 부분을 여러번 해서 심층화된 학습을 시키려고 ? 아무튼 이런 뜻 여러번 쓸수록 정확도가 높아짐 but 속도가 느려짐
            tf.keras.layers.Dense(3, activation=tf.nn.softmax)
        ])
        #4. 모델 컴파일
        self.model.compile(optimizer='adam',
                      loss='sparse_categorical_crossentropy',
                      metrics=['accuracy'])
        #모델 훈련
        self.model.fit(x_train, y_train, epochs=214)
        self.model.save("gawi.h5")
 
if __name__ == '__main__':
    ag = AaoGawi()
    ag.run_makeh5()
    
    
    
    
    
cs



 

'daily > AI' 카테고리의 다른 글

[AI] BeautifulSoup  (0) 2023.04.25
[AI] OpenCV  (0) 2023.04.22
[AI] cifar10  (0) 2023.04.20
[AI] tensorflow (2)  (0) 2023.04.19
[AI] tensorflow (1)  (0) 2023.04.19