quilt code

[AI] tensorflow (1) 본문

daily/AI

[AI] tensorflow (1)

김뱅쇼 2023. 4. 19. 21:08

tensorflow 기본 연습

 


1. my_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
import tensorflow as tf
 
#데이터셋임포트
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("x_train",x_train)
#데이터 전처리
x_train, x_test = x_train/255.0, x_test/255.0 #신경망이 읽을 수 있게 숫자를 압축해줌 => 시그모이드 함수 사용할 수 있음1
#모델 구성
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(2828)),
    tf.keras.layers.Dense(512, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
#4. 모델 컴파일
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
#모델 훈련
model.fit(x_train, y_train, epochs=5)
 
#정확도 평가
test_loss, test_acc = model.evaluate(x_test, y_test)
print('테스트 정확도:', test_acc)
cs
mnist = tf.keras.datasets.mnist : 저장된 데이터를 불러옴

(x_train, y_train), (x_test, y_test) = mnist.load_data() : 데이터 학습(기출) / 학습된 데이터를 테스트해봄(수능)

x_train, x_test = x_train/255.0, x_test/255.0 : 신경망이 읽을 수 있게 숫자를 압축해주는  과정

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),            : 입력층,  28,28인 이유? 그냥.. 뭐 면이어서? 라고는 하는데 확실하게는 모르겠다
    tf.keras.layers.Dense(512, activation=tf.nn.relu),        : 은닉층
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)    : 출력층
]

model.compile(optimizer='adam',                               :  여기는 그냥 그런거라고 생각하고 넘어가자 
              loss='sparse_categorical_crossentropy',       
              metrics=['accuracy'])                                      : accuracy가 높을 수록 안정된 데이터를 얻을 수 있음

model.fit(x_train, y_train, epochs=5)  : 모델 훈련 epochs 모델 훈련 횟수. 안 쓰면 default 값으로 훈련

 


2. my_mnist02_data



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
import tensorflow as tf
import cv2
 
mnist = tf.keras.datasets.mnist
#load data 데이터를 가져옴 
#튜플(,) 두개를 줌
(x_train, y_train), (x_test, y_test) = mnist.load_data()
 
 
print("x_train",x_train)
print("y_train",y_train)
print("x_test",x_test)
print("y_test",y_test)
 
print("x_train",x_train.shape)
print("y_train",y_train.shape) #numpy 안에 있는 배열의 개수를 알려줌....? .shape
print("x_test",x_test.shape)
print("y_test",y_test.shape)
 
print("x_train[2]",x_train[0])
print("y_train[2]",y_train[0])
 
# arr2D = x_train[2]
#
# for i in arr2D:
#     for j in i:
#         print(j,end="\t")
#     print("")
 
#방법1
# cv2.imwrite('img/'+str(0)+'jpg', x_train[0])
# cv2.imwrite('img/'+str(1)+'.jpg', x_train[1])
 
#방법2
# cv2.imwrite('img/{}.jpg'.format(0), x_train[0])
# cv2.imwrite('img/{}.jpg'.format(1), x_train[0])
 
for idx,i in enumerate(x_train):
    label = y_train[idx]
    if label == 0:
        cv2.imwrite('img/0/{}.jpg'.format(idx), x_train[idx])
    if label == 1:
        cv2.imwrite('img/1/{}.jpg'.format(idx), x_train[idx])
    if label == 2:
        cv2.imwrite('img/2/{}.jpg'.format(idx), x_train[idx])
    if label == 3:
        cv2.imwrite('img/3/{}.jpg'.format(idx), x_train[idx])
    if label == 4:
        cv2.imwrite('img/4/{}.jpg'.format(idx), x_train[idx])
    if label == 5:
        cv2.imwrite('img/5/{}.jpg'.format(idx), x_train[idx])
    if label == 6:
        cv2.imwrite('img/6/{}.jpg'.format(idx), x_train[idx])
    if label == 7:
        cv2.imwrite('img/7/{}.jpg'.format(idx), x_train[idx])
    if label == 8:
        cv2.imwrite('img/8/{}.jpg'.format(idx), x_train[idx])
    if label == 9:
        cv2.imwrite('img/9/{}.jpg'.format(idx), x_train[idx])
    #
    # if idx > 10:
    #      break;
 
 
 
 
 
 
 
cs

cv2.imwrite(img/0/{}.jpg.format(idx), x_train[idx]) : jpg파일로 format형식을 빌어 x_train으로 학습시킨 이미지를 저장함 


3. my_mnist03_data



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
import tensorflow as tf
import cv2
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
 
print("x_train",x_train)
print("y_train",y_train)
print("x_test",x_test)
print("y_test",y_test)
 
print("x_train",x_train.shape)
print("y_train",y_train.shape)
print("x_test",x_test.shape)
print("y_test",y_test.shape)
 
print("x_train[2]",x_train[0])
print("y_train[2]",y_train[0])
 
 
for idx,i in enumerate(x_train):
    label = y_train[idx]
    cv2.imwrite('train/0/{}.jpg'.format(idx), x_train[idx])
 
for idx,i in enumerate(x_test):
    label = y_test[idx]
    cv2.imwrite('test/0/{}.jpg'.format(idx), x_test[idx])
 
 
 
 
 
 
 
 
cs

02번이랑 별로 다른게 없음

 


4. my_mnist04_numpy



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import tensorflow as tf
import numpy as np
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
 
 
np.save('x_train',x_train)
np.save('x_test',x_test)
 
 
x_train, x_test = x_train/255.0, x_test/255.0
 
 
 
 
 
 
 
 
cs


np.save('x_train',x_train)
np.save('x_test',x_test)

numpy로 저장

 


5. my_mnist05



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
import tensorflow as tf
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("x_train",x_train)
 
# 데이터 전처리
x_train, x_test = x_train/255.0, x_test/255.0    #정제 : 신경망이 읽을 수 있게 숫자를 압축해줌 => 시그모이드 함수 사용. 255인 이유? ______ 
 
# 모델 ㄱ구성
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(2828)),  # Flatten: 2차원 배열을 1차원 배열로 만듦 , 입력층을 만들어줌 
    tf.keras.layers.Dense(512, activation=tf.nn.relu),  #중간에 뉴런 512개/ 하나하나는 퍼셉트론 
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)  #출력층 : 0에서 9까지라서 10 
])
 
#모델 컴파일
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
#모델 훈련
model.fit(x_train, y_train, epochs=10)  #epochs : 몇번 훈련할지 / 역전파 
                                        #60000개 중에서 1875개를 랜덤으로 뽑아서 반복 
 
#정확도 평가 
test_loss, test_acc = model.evaluate(x_test, y_test)  #evaluate: 정확도 평가 
print('테스트 정확도:', test_acc)
 
 
cs

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),  : Flatten: 2차원 배열을 1차원 배열로 만듦 , 입력층을 만들어줌 , 평평하게 만듦
    tf.keras.layers.Dense(512, activation=tf.nn.relu),  #중간에 뉴런 512개/ 하나하나는 퍼셉트론 
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)  #출력층 : 0에서 9까지라서 10 
])


7. my_mnist06_predict



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
import tensorflow as tf
import numpy as np
import cv2
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data() # **3: x_test256
 
x_train, x_test = x_train/255.0, x_test/255.0 # **2: 이미지가 안 뜨는 현상 고치기 : or x_test256으로 바꾸기
 
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(2828)),
    tf.keras.layers.Dense(512, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
 
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']) #accuracy가 중요함... 이게 높아질수록 안정된 데이터를 얻을 수 있다
 
model.fit(x_train, y_train, epochs=5)
 
print("x_test",x_test.shape) #뇌의 모양 확인 
 
#예측하기 ★★★ 훈련 뒤 얼마나 예측을 잘 하는지, 훈련한것을 바탕으로 예측함 
predict = model.predict(x_test)
 
 
cnt_o = 0 
cnt_x = 0
for i in range(10000):
    pred = np.argmax(predict[i])  #argmax: numpy 안에서 최대값의 index를 보여줌 (배열에는 못 쓰고 numpy에서만 사용) 
    goog = y_test[i]
    if pred == goog:
        cnt_o += 1
    else:
        cnt_x += 1
        print("i",i,"pred",pred,"goog",goog)
        # i번호_pred_goog.jpg로 fault 폴더에 저장하기(틀린 것들만 뽑아내기)
        print("{}_{}_{}".format(i,pred,goog))
        cv2.imwrite('fault/{}_{}_{}.jpg'.format(i,pred,goog), x_test[i]*255.0#255.0을 곱해야 이미지가 제대로 나옴 안 곱해주면 0만 들어가있는 상황임 **1 **4 :x_test256
 
# print("pred",np.argmax(predict[0]))  #예측한 숫자, 배열 중에 가장 확률이 높은 index를 뽑아라
# print("goog",y_test[0])   #google이 준 숫자 
 
print("cnt_o",cnt_o)
print("cnt_x",cnt_x)
 
 
 
cs

predict = model.predict(x_test)  : 모델 훈련 뒤 얼마나 예측을 잘하는지, 훈련한 것을 바탕으로 예측함


for i in range(10000):
    pred = np.argmax(predict[i])  : argmax - numpy 안에서 최대값의 index를 보여줌 (배열에는 못 쓰고 numpy에서만 사용) 
    goog = y_test[i]
    if pred == goog
        cnt_o += 1
    else:
        cnt_x += 1
        print("i",i,"pred",pred,"goog",goog)
        # i번호_pred_goog.jpg로 fault 폴더에 저장하기(틀린 것들만 뽑아내기) (pred == goog가 아닌 것들) 
        print("{}_{}_{}".format(i,pred,goog))
        cv2.imwrite('fault/{}_{}_{}.jpg'.format(i,pred,goog), x_test[i]*255.0) : fault 폴더에 해당 형식으로 jpg 파일을 만듦. 255.0을 다시 곱해야 이미지가 제대로 나옴


결과)



console에 뜬 파일이 fault 폴더에도 들어가 있음!

 


8. my_mnist07_save



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("x_train",x_train)
 
x_train, x_test = x_train/255.0, x_test/255.0
 
#모델 구성 
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(2828)),
    tf.keras.layers.Dense(512, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
 
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
 
model.fit(x_train, y_train, epochs=5)
 
#h5로 저장, 뇌가 저장된 파일(훈련이 되어있어서 가져와서 사용만 하면됨) / 모델 저장
model.save("mnist.h5")
cs



model.save("mnist.h5")  : mnist란 이름을 가진 h5파일을 만들어서 학습시킨 모델을 저장해줌. save폴더라고 생각하면 쉬움...



 


9. my_mnist08_load



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tensorflow as tf
import keras
 
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("x_train",x_train)
 
x_train, x_test = x_train/255.0, x_test/255.0
 
#뇌만 가져와서 구현
model = keras.models.load_model("mnist.h5")
 
test_loss, test_acc = model.evaluate(x_test, y_test)
print('테스트 정확도:', test_acc)
 
cs

model = keras.models.load_model("mnist.h5") : 8. my_mnist07_save 에서 만든 mnist.h5을 불러와줌. 미리 학습시키고 저장된 모델을 불러와서 구현함

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

[AI] OpenCV  (0) 2023.04.22
[AI] tensorflow (3)  (0) 2023.04.22
[AI] cifar10  (0) 2023.04.20
[AI] tensorflow (2)  (0) 2023.04.19
[AI] numpy  (0) 2023.04.17