728x90

기본 환경: IDE: VS code, Language: Python

 

Sequence data(음성인식이라던지 자연어라던지 등의 문맥이 있는 데이터)의 경우, 이전의 단어들을 이해해야 전체의 맥락을 이해 할 수 있으나 맥락들이 있는 series 데이터는 이전 상태를 전달하지 않는 DNN/CNN에서 사용하기 어려움

 

⭐ RNN은 상태(state)를 계산할때는 이전 상태(state)를 사용하여, 이전 연산값이 bias처럼 영향을 미치면서 미래의 predict에 영향을 미침

 

RNN 작동원리

 

RNN 작동원리 활용 예제

1. I가 ProNoun일 확률이 높다는 것을 다음 layer에 전달

2. 이전 값이 ProNoun일 확률이 높으므로 work는 동사일 확률이 높다는 것이 work에 품사 결정에 영향

... 의 반복

 

 

⚠️ RNN의 경우, 장기 의존성(Longterm Dependency) 문제 발생

 

LSTM(Long Short Term Memory)

 

 

1. 삭제 게이트(forget gate)

: 장기 상태의 어느 부분이 삭제되어야 하는지 제어하는 역할

: Activatoin Function: Sigmoid

: 결과값이 0에 가까울수록 정보가 많이 삭제된 것이고, 1에 가까울수록 온전한 상태에 가까운 것

 

2. 입력 게이트(input gate)

: 장기 상태의 어느 부분이 기억되어야 하는지 제어하는 역할

:  Activation Function: Sigmoid, Tanh

 

3. 셀 상태(장기 상태)

C(t-1) -> C(t): 삭제 게이트와 입력 게이트를 거쳐서 만들어지는 셀

-> 삭제 게이트: 이전 시점의 입력을 얼마나 반영할지 제어

-> 입력 게이트: 현재 시점의 입력을 얼마나 반영할지 제어

 

4. 출력 게이트와 은닉 상태(단기 상태)

: 장기 상태의 어느 부분을 읽어서 현재 시점의 어떤 값으로 출력해야하는지 제어

 

SimpleRNN보다 gate가 4배이므로 연산량도 4배

 

 

GRU(Gated Recurrent Units)

: LSTM을 기반으로 만들어진 모델로 더 간략한 구조를 통해 비슷한 성능에 빠른 속도를 구현

: 업데이트 게이트와 리셋 게이트 두 가지 게이트만이 존재

1. Reset Gate

: 과거의 정보를 적당히 reset 시키는 목적

2. Update Gate

: 과거와 현재 정보의 최신화 비율을 결정

3. Candidate

: 현 시점의 정보 후보군을 계산

 

 SimpleRNN보다 gate가 3배이므로 연산량도 3배였으나, version update로 인해서 연산량 변경

 

 

⭐ Model Summary(RNN, LSTM, GRU)

# calc_param_RNN_LSTM_GRU.py

import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU, Dropout


# 1. Data
dataset=np.array([1,2,3,4,5,6,7,8,9,10]) # (10,)
# absence y data

# make a y data
x = np.array([[1,2,3], 
              [2,3,4], 
              [3,4,5], 
              [4,5,6], 
              [5,6,7], 
              [6,7,8], 
              [7,8,9]]) # (7, 3)
y = np.array([4,5,6,7,8,9,10]) # (7,)
# y = np.array([[4],[5],[6],[7],[8],[9],[10]]) 과 동일

x = x.reshape(7,3,1)


# 2. Model Construction
model = Sequential()
# model.add(SimpleRNN(units=64, input_length=3, input_dim=1))
# model.add(LSTM(units=10, input_shape=(3,1)))
model.add(GRU(units=10, input_shape=(3,1)))
model.add(Dense(1))
model.summary()
'''
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 simple_rnn (SimpleRNN)      (None, 10)                120
-----------------------------------------------------------------
 lstm (LSTM)                 (None, 10)                480
-----------------------------------------------------------------
 gru (GRU)                   (None, 10)                390
_________________________________________________________________

SimpleRNN Param #
Total params = recurrent_weights + input_weights + biases
= (units*units)+(features*units) + (1*units)
= units(units + feature + 1)


LSTM Param #
Params # = 4 * (output_dim(output_dim + input_dim + 1))
= 4 * SimpleRNN (gate가 4개라서 SimpleRNN의 4배)


(Deprecated) GRU Param #
Params # = 3 * ((input_dim + 1) * output_dim + output_dim^2)
= 3 * SimpleRNN (gate가 3개라서 SimpleRNN의 3배)


(Renew) GRU Param #
Params # = 3 * output_dim * (input_dim + bias + reset_after bias + output_dim)
(reset_after=False: 3 * output_dim * (input_dim + bias + output_dim))
-> 3 * 10 * (1 + 1 + 1 + 10)
(Default: reset_after=True)

'''

 

➕ data 생성 후, 다양한 모델에 적용하기

# split_x_with_application_model.py

import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU, Conv2D, Flatten, Dropout


# Prepare Total data
a = np.array(range(1,11)) # 1~10
timesteps = 5

def split_x(dataset, timesteps):
    li = [] # 빈 list 생성
    for i in range(len(dataset) - timesteps + 1):
        # for i in range(3->range(3): 0, 1, 2), range(4->2), range(5->1) : 반환하는 리스트 개수
        subset = dataset[i: (i+timesteps)]
        # dataset[0(이상):3(미만)] [1:4] [2:5]: dataset 위치에 있는 값 반환
        li.append(subset) # append: 추가
    return np.array(li)
'''
timesteps = 5
[[1 2 3 4 5]]

timesteps = 4
[[1 2 3 4]
 [2 3 4 5]]
 
 timesteps = 3
 [[1 2 3]
 [2 3 4]
 [3 4 5]] 
'''

total_Data = split_x(a, timesteps)
print(total_Data)
'''
[[ 1  2  3  4  5]
 [ 2  3  4  5  6]
 [ 3  4  5  6  7]
 [ 4  5  6  7  8]
 [ 5  6  7  8  9]
 [ 6  7  8  9 10]]
'''
print(total_Data.shape) # (6, 5)

# 1-2. make x, y data
x = total_Data[:, :-1] # 모든 행, 시작 ~ -2번째 열
y = total_Data[:, -1] # 모든 행, -1번째 열(시작: 0번째 열)

print(x, y)
'''
x: 
[[1 2 3 4]
 [2 3 4 5]
 [3 4 5 6]
 [4 5 6 7]
 [5 6 7 8]
 [6 7 8 9]]
 
 y:
 [ 5  6  7  8  9 10]
= [5][6][7][8][9][10]

'''


# RNN
x=x.reshape(6,4,1)
# LSTM input_shape=3

model1 = Sequential()
model1.add(LSTM(units=64, input_shape=(4,1)))
# model.add(SimpleRNN(units=64, input_shape=(4,1)))
# model.add(GRU(units=64, input_shape=(4,1)))
model1.add(Dense(32, activation='relu'))
model1.add(Dropout(0.2))
model1.add(Dense(16, activation='relu'))
model1.add(Dropout(0.1))
model1.add(Dense(16, activation='relu'))
model1.add(Dense(1))
model1.summary()

'''
cf.
x = x.reshape(96,2,2)
# data feature가 홀수일 때는 reshape이 불가능하므로, 처음부터 data set을 짝수로 구비하기

model.add(LSTM(units=64, input_shape=(2,2)))
# reshape 시, timesteps*feature가 유지되도록 reshape
'''


# DNN
# Dense input_shape=2이상

model2 = Sequential()
model2.add(Dense(32, activation='relu', input_shape=(4,)))
model2.add(Dense(16, activation='relu'))
model2.add(Dense(16, activation='relu'))
model2.add(Dense(4, activation='relu'))
model2.add(Dense(1))


# Cov2D
x = x.reshape(96,2,2,1)
# Conv2D input_shape=4

model3 = Sequential()
model3.add(Conv2D(32, (2,2), padding='same', activation='relu', input_shape=(2,2,1)))
model3.add(Flatten())
model3.add(Dense(16, activation='relu'))
model3.add(Dense(16, activation='relu'))
model3.add(Dense(4, activation='relu'))
model3.add(Dense(1))

 

RNN Model Construction

# rnn_model.py

import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint


# 1. Data
x = np.array([[1,2,3], 
              [2,3,4], 
              [3,4,5], 
              [4,5,6], 
              [5,6,7], 
              [6,7,8], 
              [7,8,9],
              [8,9,10], 
              [9,10,11], 
              [10,11,12], 
              [20,30,40], 
              [30,40,50], 
              [40,50,60]]) # (13, 3)
y = np.array([4,5,6,7,8,9,10,11,12,13,50,60,70]) # (13,)

x=x.reshape(13,3,1)
x_predict = np.array([50,60,70]).reshape(1,3,1)
# RNN, LSTM, GRU Model Input_dim: 3 -> reshape
# input_dim=1일 경우, reshape 생략이 가능하나 통일성을 위해 reshape 작성


# 2. Model Construction
model = Sequential()
model.add(LSTM(units=64,
               input_shape=(3,1),
               return_sequences='True'))
# input_shape(3,1): input_length=3, input_dim=1
# conv2D : input_dim 4 -> output_dim 4
# RNN, LSTM, GRU: input_dim=3 -> output_dim=2 / # (N,3,1) -> (N, 64)
# return_sequences = True: (None, 3, 64) input_dim만 units로 변화
model.add(SimpleRNN(units=64))
# model.add(GRU(units=64))
# ValueError: Input 0 of layer "lstm_1" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 64)
# return sequence=True 처리 시, shape이 유지되므로 RNN Model 연이어 사용 가능
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(32, activation='relu'))
model.add(Dense(16))
model.add(Dense(1))
model.summary()


# 3. Compile and Training
model.compile(loss='mse', optimizer='adam')

earlyStopping = EarlyStopping(monitor='loss', mode='min', patience=32,
                              restore_best_weights=True,
                              verbose=1)

model.fit(x, y, epochs=512, callbacks=[earlyStopping], batch_size=1)


# 4. Evaluation and Prediction
loss = model.evaluate(x,y)
print("Loss: ", loss)

result = model.predict(x_predict)
print("Predict[50,60,70]: ", result)



'''
Result
Loss:  2.875849485397339
Predict[50,60,70]:  [[80.20353]]

'''

 

⭐ DNN, CNN, RNN data / input / output shape

Model Data Input_shape(Data_shape-1) Output_shape
DNN 2차원 이상 1차원 2차원 이상(Data_shape 변형 X)
CNN 4차원 3차원 4차원
RNN 3차원 2차원 3차원

 

 

 

소스 코드

🔗 HJ0216/TIL

 

참고 자료

📑 RNN(Recurrent Neural Network, 순환신경망)을 이해해보자

📑 [RNN] 파라미터 개수 카운팅

📑 i) LSTM

📑 05.20(LSTM의 첫번째 파라미터 값) 송정현

📑 RNN, LSTM,GRU

📑 keras

📑 tensorflow

📹 [딥러닝] RNN 기초 (순환신경망 - Vanilla RNN)

📑 07-3. 순환 신경망 LSTM, GRU - (3)

📑 Gated Recurrent Units (GRU)

 

728x90
728x90

이 글은 양주종의 코딩스쿨 리눅스(Linux) 기초 강좌 30강 모음 수강하며 정리한 글입니다.

 

18강 C언어코딩(gcc)

(일반 사용자 id: j, pw: j)

(관리자 id: root, pw: r)

 

gcc C언어 complier 설치

[j@hj0216 ~]$ su -
암호:
마지막 로그인: 목  1월 26 01:38:48 KST 2023일시 pts/0
[root@hj0216 ~]# yum -y install gcc
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.navercorp.com
 * extras: mirror.navercorp.com
 * updates: mirror.navercorp.com
Resolving Dependencies
--> Running transaction check
---> Package gcc.x86_64 0:4.8.5-44.el7 willbe installed
--> Processing Dependency: libgomp = 4.8.5-44.el7 for package: gcc-4.8.5-44.el7.x86_64
--> Processing Dependency: cpp = 4.8.5-44.el7 for package: gcc-4.8.5-44.el7.x86_64
--> Processing Dependency: libgcc >= 4.8.5-44.el7 for package: gcc-4.8.5-44.el7.x86_64
--> Processing Dependency: glibc-devel >= 2.2.90-12 for package: gcc-4.8.5-44.el7.x86_64
--> Processing Dependency: libmpfr.so.4()(64bit) for package: gcc-4.8.5-44.el7.x86_64
--> Processing Dependency: libmpc.so.3()(64bit) for package: gcc-4.8.5-44.el7.x86_64
--> Running transaction check
---> Package cpp.x86_64 0:4.8.5-44.el7 willbe installed
---> Package glibc-devel.x86_64 0:2.17-326.el7_9 will be installed
--> Processing Dependency: glibc-headers = 2.17-326.el7_9 for package: glibc-devel-2.17-                                  326.el7_9.x86_64
--> Processing Dependency: glibc = 2.17-326.el7_9 for package: glibc-devel-2.17-326.el7_                                  9.x86_64
--> Processing Dependency: glibc-headers for package: glibc-devel-2.17-326.el7_9.x86_64
---> Package libgcc.x86_64 0:4.8.5-36.el7 will be updated
---> Package libgcc.x86_64 0:4.8.5-44.el7 will be an update
---> Package libgomp.x86_64 0:4.8.5-36.el7 will be updated
---> Package libgomp.x86_64 0:4.8.5-44.el7 will be an update
---> Package libmpc.x86_64 0:1.0.1-3.el7 will be installed
---> Package mpfr.x86_64 0:3.1.1-4.el7 will be installed
--> Running transaction check
---> Package glibc.x86_64 0:2.17-260.el7 will be updated
--> Processing Dependency: glibc = 2.17-260.el7 for package: glibc-common-2.17-260.el7.x                                  86_64
---> Package glibc.x86_64 0:2.17-326.el7_9 will be an update
---> Package glibc-headers.x86_64 0:2.17-326.el7_9 will be installed
--> Processing Dependency: kernel-headers >=2.2.1 for package: glibc-headers-2.17-326.e                                  l7_9.x86_64
--> Processing Dependency: kernel-headers for package: glibc-headers-2.17-326.el7_9.x86_                                  64
--> Running transaction check
---> Package glibc-common.x86_64 0:2.17-260.el7 will be updated
---> Package glibc-common.x86_64 0:2.17-326.el7_9 will be an update
---> Package kernel-headers.x86_64 0:3.10.0-1160.81.1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================
 Package
        Arch   Version        Repository
                                       Size
============================================
Installing:
 gcc    x86_64 4.8.5-44.el7   base     16 M
Installing for dependencies:
 cpp    x86_64 4.8.5-44.el7   base    5.9 M
 glibc-devel
        x86_64 2.17-326.el7_9 updates 1.1 M
 glibc-headers
        x86_64 2.17-326.el7_9 updates 691 k
 kernel-headers
        x86_64 3.10.0-1160.81.1.el7
                              updates 9.1 M
 libmpc x86_64 1.0.1-3.el7    base     51 k
 mpfr   x86_64 3.1.1-4.el7    base    203 k
Updating for dependencies:
 glibc  x86_64 2.17-326.el7_9 updates 3.6 M
 glibc-common
        x86_64 2.17-326.el7_9 updates  12 M
 libgcc x86_64 4.8.5-44.el7   base    103 k
 libgomp
        x86_64 4.8.5-44.el7   base    159 k

Transaction Summary
============================================
Install  1 Package  (+6 Dependent packages)
Upgrade             ( 4 Dependent packages)

Total download size: 49 M
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
(1/11): glibc-devel-2. | 1.1 MB   00:01
(2/11): glibc-2.17-326 | 3.6 MB   00:02
(3/11): glibc-headers- | 691 kB   00:01
(4/11): libgcc-4.8.5-4 | 103 kB   00:00
(5/11): libgomp-4.8.5- | 159 kB   00:00
(6/11): libmpc-1.0.1-3 |  51 kB   00:00
(7/11): mpfr-3.1.1-4.e | 203 kB   00:00
(8/11): cpp-4.8.5-44.e | 5.9 MB   00:04
(9/11): glibc-common-2 |  12 MB   00:04
(10/11): gcc-4.8.5-44. |  16 MB   00:06
(11/11): kernel-header | 9.1 MB   00:04
--------------------------------------------
Total          6.3 MB/s |  49 MB  00:07
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Updating   : libgcc-4.8.5-44.el7.    1/15
  Updating   : glibc-common-2.17-32    2/15
  Updating   : glibc-2.17-326.el7_9    3/15
warning: /etc/nsswitch.conf created as /etc/nsswitch.conf.rpmnew
  Installing : mpfr-3.1.1-4.el7.x86    4/15
  Installing : libmpc-1.0.1-3.el7.x    5/15
  Installing : cpp-4.8.5-44.el7.x86    6/15
  Updating   : libgomp-4.8.5-44.el7    7/15
  Installing : kernel-headers-3.10.    8/15
  Installing : glibc-headers-2.17-3    9/15
  Installing : glibc-devel-2.17-326   10/15
  Installing : gcc-4.8.5-44.el7.x86   11/15
  Cleanup    : libgomp-4.8.5-36.el7   12/15
  Cleanup    : glibc-common-2.17-26   13/15
  Cleanup    : glibc-2.17-260.el7.x   14/15
  Cleanup    : libgcc-4.8.5-36.el7.   15/15
  Verifying  : kernel-headers-3.10.    1/15
  Verifying  : glibc-headers-2.17-3    2/15
  Verifying  : glibc-2.17-326.el7_9    3/15
  Verifying  : mpfr-3.1.1-4.el7.x86    4/15
  Verifying  : glibc-devel-2.17-326    5/15
  Verifying  : cpp-4.8.5-44.el7.x86    6/15
  Verifying  : gcc-4.8.5-44.el7.x86    7/15
  Verifying  : libmpc-1.0.1-3.el7.x    8/15
  Verifying  : glibc-common-2.17-32    9/15
  Verifying  : libgcc-4.8.5-44.el7.   10/15
  Verifying  : libgomp-4.8.5-44.el7   11/15
  Verifying  : glibc-2.17-260.el7.x   12/15
  Verifying  : libgomp-4.8.5-36.el7   13/15
  Verifying  : libgcc-4.8.5-36.el7.   14/15
  Verifying  : glibc-common-2.17-26   15/15

Installed:
  gcc.x86_64 0:4.8.5-44.el7

Dependency Installed:
  cpp.x86_64 0:4.8.5-44.el7
  glibc-devel.x86_64 0:2.17-326.el7_9
  glibc-headers.x86_64 0:2.17-326.el7_9
  kernel-headers.x86_64 0:3.10.0-1160.81.1.el7
  libmpc.x86_64 0:1.0.1-3.el7
  mpfr.x86_64 0:3.1.1-4.el7

Dependency Updated:
  glibc.x86_64 0:2.17-326.el7_9
  glibc-common.x86_64 0:2.17-326.el7_9
  libgcc.x86_64 0:4.8.5-44.el7
  libgomp.x86_64 0:4.8.5-44.el7

Complete!
[root@hj0216 ~]# rpm -qa | grep gcc
libgcc-4.8.5-44.el7.x86_64
gcc-4.8.5-44.el7.x86_64

1. root 계정 로그인

2. gcc install

3. gcc pkg 설치 조회

 

 

c언어 파일 만들기 및 실행하기

[j@hj0216 ~]$ vi t.c

On vim editor
	  1 #include <stdio.h>
      2 int main(void)
      3 {
      4         puts("Linux\n");
      5         return 0;
      6 }

[j@hj0216 ~]$ gcc t.c
[j@hj0216 ~]$ ls
a.out  bbb  dd  ddd  t.c
[j@hj0216 ~]$ ./a.out
Linux

gcc 컴파일러로 t.c 파일을 컴파일 → a.out 실행 파일 생성 → 생성된 a.out 파일을 이용하여 파일 실행 
컴파일 과정에서 실행파일의 이름을 지정해 주지 않으면 기본적으로 a.out 이라는 이름으로 실행파일이 생성

 

파일 실행 관련 PATH 지정

[j@hj0216 ~]$ a.out
-bash: a.out: command not found
[j@hj0216 ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/j/.local/bin:/home/j/bin
[j@hj0216 ~]$ PATH=$PATH:. # PATH에 현재 dir 추가
[j@hj0216 ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/j/.local/bin:/home/j/bin:.
[j@hj0216 ~]$ a.out
Linux

파일 경로를 찾을 때, 현재 dir이 PATH에 지정되어있지 않으므로 a.out 파일 실행 시 경로지정이 필요

일반 사용자 계정에서 설정한 PATH는 로그아웃 시 사라짐

 

gcc를 통한 c언어 파일 이름 지정

[j@hj0216 ~]$ gcc t.c -o aa
[j@hj0216 ~]$ ls
a.out  aa  bbb  dd  ddd  t.c
[j@hj0216 ~]$ a.out
Linux

[j@hj0216 ~]$ aa
Linux

-o 실행파일명: a.out이 아닌 새로운 실행파일명 지정

 

 

 

➕ C언어 컴파일 과정

1. C언어 파일 작성(vi hello.c)

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("Hello World!\n");

    return 0;
}

 

2. PreProcessing, PreComplie

 - #으로 시작하는 부분은 C complier가 쉽게 인식할 수 있도록 C언어 소스로 재정리

 - /* ~ */과 같은 주석 제거

 - #include: header file의 내용을 읽고 필요한 내용을 복사

 - #define: 치환 작업 진행

-> gcc compiler: hello.i 파일 내부 생성

# 1 "hello.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "hello.c"

# 1 "/usr/include/stdio.h" 1 3 4
# 28 "/usr/include/stdio.h" 3 4

... 중략 ...

# 211 "/usr/lib/gcc/x86_64-redhat-linux/4.4.7/include/stddef.h" 3 4
typedef long unsigned int size_t;

... 중략 ...

extern int printf (__const char *__restrict __format, ...);

... 중략 ...

int main(int argc, char **argv)
{
    printf("Hello World!\n");

    return 0;
}

 

3. Compile(Assembler 코드 생성)

 - 전처리가 끝난 소스코드(hello.i)를 기반으로 assembler 소스코드 생성

-> hello.s 파일 생성

        .file   "hello.c"
        .section        .rodata
.LC0:
        .string "Hello World!"
        .text
.globl main
        .type   main, @function
main:
.LFB0:
        .cfii_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        
... 이하 생략 ...

 

4. Assemble(Object 파일 생성)

Assembler source(hello.s)를 바탕으로 목적(Object) 파일 생성(기계어 코드)

^?ELF^B^A^A^@^@^@^@^@^@^@^@^@^@^@^A^@>^ ..... 생략 .....

 

5. Link(실행 파일 생성)

obj 파일은 직접 실행할 수 없으므로 실행 파일로 만들기 위해 Link 작업 실시

C언어는 분할 컴파일이 가능하여, A라는 기능을 하는 파일과 B라는 기능을 하는 파일을 따로 만들어서 컴파일을 해서 링크 작업을 통해 여러 파일의 기능을 합쳐서 실행 파일을 만들 수 있음

실행파일도 분할 컴파일을 이용하여 hello.o와 표준 라이브러리인 a 또는 .so 파일을 합쳐서 만들어짐

^?ELF^B^A^A^@^@^@^@^@^@^@^@^@^@^@^A^@>^ ..... 생략 .....

 

# C언어 Compile 과정
    1). 소스 코딩 →  hello.c 
    2). hello.c → preprocess (전처리)  →  hello.i 
    3). hello.i →  컴파일 →  hello.s
    4). hello.s →  Assemble → hello.o
    5). hello.o + library →  Link → hello

 

참고 자료

📑 [ 리눅스 ] gcc 동작과정

📑 3. C언어의 컴파일 과정

📑 [ Linux ] linux 환경 C 컴파일 과정 & make 의 이해

 

728x90
728x90

이 글은 양주종의 코딩스쿨 리눅스(Linux) 기초 강좌 30강 모음 수강하며 정리한 글입니다.

 

17강 vim 편집기

(일반 사용자 id: j, pw: j)

(관리자 id: root, pw: r)

 

vim editor 시작

[j@hj0216 ~/dd]$ vi
# 이름없는 파일에서 작업, 저장 시 이름 부여 필요
[j@hj0216 ~/dd]$ vi a1
# a1 파일 내용 수정
[j@hj0216 ~/dd]$ vi a2
# a2 파일 생성

esc: 작업 종료

i 끼워넣기

:w 저장

:w 파일이름 '파일이름'으로 저장

:q 종료

:q! 강제 종료

:wq 저장 후 종료

:se nu 행번호 부여

:se nonu 행번호 삭제

dd 1줄씩 지우기

 

vimtutor

[j@hj0216 ~/dd]$ vimtutor
                             LESSON 1 요약

  1. 커서를 움직일 때에는 화살표 키나 hjkl 키를 이용합니다.
         h (왼쪽)       j (아래)       k (위)       l (오른쪽)
  2. 쉘 프롬프트에서 빔을 시작하려면 vim FILENAME <ENTER>
  3. 수정한 내용을 무시한 채로 빔에서 빠져나가려면   <ESC>   :q!   <ENTER>
                     저장한 후 빔에서 빠져나가려면   <ESC>   :wq   <ENTER>
  4. 명령 모드에서 커서가 위치한 곳의 글자를 지우려면   x  를 입력합니다.
  5. 명령 모드에서 커서가 위치한 곳에 텍스트를 삽입하려면
         i   를 누른 후 텍스트를 입력하고  <ESC> 를 누릅니다.
참고: <ESC>는 명령 모드로 돌아가는 데 쓰며, 원치 않는 명령이나 완전히 입력되지
      않은 명령을 취소하는 데에도 씁니다.
                               LESSON 2 요약
                               
  1. 커서가 위치한 곳부터 단어의 끝까지 지우려면:    dw
  2. 커서가 위치한 곳부터 줄 끝까지 지우려면:    d$
  3. 줄 전체를 지우려면:    dd
  4. 명령 모드에서 내리는 명령의 형식은 다음과 같습니다:
       [횟수]   명령   대상    또는    명령   [횟수]   대상
     여기서:
       횟수 - 그 명령을 몇 번 반복할 것인가
       명령 - 어떤 명령을 내릴 것인가 ( 예를 들어, 삭제인 경우는 d )
       대상 - 명령이 동작할 대상, 예를 들어 w (단어), $ (줄의 끝) 등.
  5. 이전 행동을 취소하려면:                 u   (소문자 u)
     한 줄에서 수정한 것을 모두 취소하려면:  U   (대문자 U)
     취소한 것을 다시 실행하려면:            CTRL-R
                               LESSON 3 요약

  1. 이미 지운 내용을 되돌리려면,  p  를 누르십시오. 이 명령은 커서 *다음에*
     지워진 내용을 붙입니다(PUT). (한 줄을 지운 경우에는 커서 다음 줄에
     지워진 내용이 붙습니다.)
  2. 커서 아래의 글자를 치환하려면(REPLACE),  r  을 누른 후 원래 글자 대신
     바꾸어 넣을 글자를 입력합니다.
  3. 변환 명령(CHANGE)은 커서에서 부터 지정한 대상의 끝까지 바꿀 수 있는
     명령입니다. 예를 들어, 커서 위치에서 단어의 끝까지 바꾸려면,  cw  를
     입력하면 되며,  c$  는 줄 끝까지 바꾸는 데 쓰입니다.
  4. 변환 명령의 형식은 다음과 같습니다:
         [횟수]   c   대상       또는       c   [횟수]   대상
                               LESSON 4 요약

  1. CTRL-g  는 파일의 상태와 파일 내에서의 현재 위치를 표시합니다.
     SHIFT-G  는 파일의 끝으로 이동합니다. 줄번호를 입력한 후 SHIFT-G를
     입력하면, 그 줄로 이동합니다.
  2.  / 를 입력한 후 문구를 입력하면 그 문구를 아랫방향으로 찾습니다.
      ? 를 입력한 후 문구를 입력하면 윗방향으로 찾습니다.
     검색 후, n 을 입력하면 같은 방향으로 다음 문구를 찾으며,
     Shift-N 을 입력하면 반대 방향으로 찾습니다.
  3. 커서가 (,),[,],{,} 위에 있을 때에  % 를 입력하면 상응하는 짝을
     찾아갑니다.

  4. 어떤 줄에 처음 등장하는 old를 new로 바꾸려면          :s/old/new
     한 줄에 등장하는 모든 old를 new로 바꾸려면            :s/old/new/g
     두 줄 #,# 사이에서 치환을 하려면                      :#,#s/old/new/g
     바꿀 때마다 확인을 거치려면 'c'를 붙여서              :%s/old/new/gc
                               LESSON 5 요약

  1.  :!command  를 이용하여 외부 명령을 실행합니다.
      유용한 예:
         (MS-DOS)         (Unix)
          :!dir            :!ls            -  디렉토리의 목록을 보여준다.
          :!del FILENAME   :!rm FILENAME   -  FILENAME이라는 파일을 지운다.
  2.  :w FILENAME  하면 현재 빔에서 사용하는 파일을 FILENAME이라는 이름으로
      디스크에 저장합니다.
  3.  :#,#w FILENAME  하면 #부터 #까지의 줄을 FILENAME이라는 파일로 저장합니다
.
  4.  :r FILENAME  은 디스크에서 FILENAME이라는 파일을 불러들여서 커서 위치
      뒤에 현재 파일을 집어넣습니다.
                               LESSON 6 요약

  1.  o 를 입력하면 커서 *아래에* 한 줄이 열리며, 커서는 편집 모드로
     열린 줄 위에 위치하게 됩니다.
     대문자  O  를 입력하면 커서가 있는 줄의 *위로* 새 줄을 열게 됩니다.
  2.  a 를 입력하면 커서 *다음에* 글을 입력할 수 있습니다.
     대문자  A  를 입력하면 자동으로 그 줄의 끝에 글자를 추가하게 됩니다.
  3. 대문자  R  을 입력하면 <ESC> 를 눌러서 나가기 전까지 바꾸기 모드가 됩니다
.
  4. ":set xxx" 를 하면 "xxx" 옵션이 설정됩니다.

 

728x90
728x90

이 글은 양주종의 코딩스쿨 리눅스(Linux) 기초 강좌 30강 모음 수강하며 정리한 글입니다.

 

16강 패키지 관리(rpm/yum)

(일반 사용자 id: j, pw: j)

(관리자 id: root, pw: r)

 

관리자로 로그인

login as: j
j@127.0.0.1's password:
Last login: Tue Jan 24 21:43:10 2023 from gateway
[j@hj0216 ~]$ su -
암호:
마지막 로그인: 일  1월 15 22:50:18 KST 2023 일시 tty1
[root@hj0216 ~]# exit
[j@hj0216 ~]$

➕ ctrl d: logout

 

Linux package = Window program

설치된 pkg 목록 조회

[root@hj0216 ~]# rpm -qa | nl
[root@hj0216 ~]# rpm -qa > rpmList

rpm: redhat package manager

→ 레드햇 계열의 리눅스 배포판에서 사용하는 프로그램(패키지) 설치 관리 도구

-qa:query all

nl: number line

rpm -qa > rpmList: 최초 설치 pkg 목록 rpmList라는 파일을 생성해서 저장

 

설치된 pkg 목록 검색

[root@hj0216 ~]# rpm -qa | grep ftp

grep ftp: ftp 문자열이 들어간 설치 pkg 목록 조회

 

pkg 설치 전 네트워크 연결 확인 test

[root@hj0216 ~]# ping -c3 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=33.7 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=54 time=36.4 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=54 time=35.2 ms

--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 33.710/35.135/36.493/1.147 ms

 

pkg 설치

[root@hj0216 ~]# yum -y install ftp
Loaded plugins: fastestmirror
Determining fastest mirrors
 * base: mirror.navercorp.com
 * extras: mirror.navercorp.com
 * updates: mirror.navercorp.com
base                 | 3.6 kB     00:00
extras               | 2.9 kB     00:00
updates              | 2.9 kB     00:00
(1/4): base/7/x86_64/g | 153 kB   00:00
(2/4): extras/7/x86_64 | 249 kB   00:00
(3/4): base/7/x86_64/p | 6.1 MB   00:03
(4/4): updates/7/x86_6 |  19 MB   00:08
Resolving Dependencies
--> Running transaction check
---> Package ftp.x86_64 0:0.17-67.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================
 Package
       Arch     Version        Repository
                                       Size
============================================
Installing:
 ftp   x86_64   0.17-67.el7    base    61 k

Transaction Summary
============================================
Install  1 Package

Total download size: 61 k
Installed size: 96 k
Downloading packages:
경고: /var/cache/yum/x86_64/7/base/packages/ftp-0.17-67.el7.x86_64.rpm: Header V3 RSA/SH                                  A256 Signature, key ID f4a80eb5: NOKEY
Public key for ftp-0.17-67.el7.x86_64.rpm is not installed
ftp-0.17-67.el7.x86_64 |  61 kB   00:00
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb124c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-6.1810.2.el7.centos.x86_64 (@anaconda)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : ftp-0.17-67.el7.x86_64   1/1
  Verifying  : ftp-0.17-67.el7.x86_64   1/1

Installed:
  ftp.x86_64 0:0.17-67.el7

Complete!
[root@hj0216 ~]# rpm -qa | grep ftp
ftp-0.17-67.el7.x86_64

yum -y install ftp: ftp 관련 pkg 설치

-y: 설치 확인 질문에 대해 미리 y 응답

 

pkg 삭제

[root@hj0216 ~]# rpm -e ftp
[root@hj0216 ~]# rpm -qa | grep ftp

-e: erase

 

 

 

728x90
728x90

기본 환경: IDE: VS code, Language: Python

 

CNN(Convolution Neural Network, 합성곱 신경망)

: 영상처리에 많이 활용되는 합성곱을 사용하는 신경망 구조

기존처럼 데이터에서 지식을 추출해 학습하는 것이 아니라 데이터의 특징을 추출하여 특징들의 패턴을 파악하는 구조

 

Conv2D with Maxpooling

# cnn_conv2D_maxPooling2D.py

import numpy as np

from tensorflow.keras.datasets import mnist, cifar10, cifar100
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D
# Maxpooling: 연산이 아니기때문에 model pkg가 아닌 layers pkg에 삽입, 2D: 이미지
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

path = './_save/'


# 1. data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
'''
x_train.shape: (60000, 28, 28) # 행(28), 열(28), 흑백(1-생략)인 이미지 데이터 60000개
y_train.shape: (60000,) # 이미지에 대한 값을 수치화
'''

# CNN Conv2D 처리하기 위해 4D(Tensor)화
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)

'''
# y_train에서 동일한 값의 빈도수 반환
print(np.unique(y_train, return_counts=True))
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8), # y_calss
array([5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949], dtype=int64) y_class의 개수)
'''


# 2. Model
model = Sequential()
model.add(Conv2D(filters=128,
                 kernel_size=(3, 3),
                 strides=1,
                 padding='same',
                 input_shape=(28, 28, 1),
                 activation='relu'))
'''
padding=valid
output_shape=(26,26,128)
# output shape = input_shape - kernel_size +1 (Not using padding)
padding=same
output_shape=(28,28,128)
'''
model.add(MaxPooling2D())
# output_shape=(14, 14, 128)
# Parameter=0 (연산 X)
model.add(Conv2D(filters=64,
                 kernel_size=(3, 3),
                 padding='same'))
# Sequential Model output->input이므로 입력값 작성 생략
model.add(Conv2D(filters=64,
                 kernel_size=(3, 3),
                 padding='same'))
model.add(MaxPooling2D())
model.add(Conv2D(filters=32,
                 kernel_size=(3, 3),
                 padding='same'))
model.add(Flatten()) # input_dim=7*7*32 (column)
model.add(Dense(32, activation='relu'))
# batch_size(총 훈련 필요 대상)=60000
model.add(Dropout(0.3))
model.add(Dense(10, activation='softmax')) # y_class=10
model.summary()
'''
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 conv2d (Conv2D)                 (None, 28, 28, 128)       1280

 max_pooling2d (MaxPooling2D)    (None, 14, 14, 128)       0

 conv2d_1 (Conv2D)               (None, 14, 14, 64)        73792

 conv2d_2 (Conv2D)               (None, 14, 14, 64)        36928

 max_pooling2d_1 (MaxPooling2D)  (None, 7, 7, 64)          0

 conv2d_3 (Conv2D)               (None, 7, 7, 32)          18464

 flatten (Flatten)               (None, 1568)              0

 dense (Dense)                   (None, 32)                50208 = 1568*32 + 32

 dropout (Dropout)               (None, 32)                0

 dense_1 (Dense)                 (None, 10)                330

=================================================================
Total params: 181,002
Trainable params: 181,002
Non-trainable params: 0
_________________________________________________________________
'''


# 3. Compile and train
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])
# one-hot encoding 안했으므로, sparse_categorical_crossentropy

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)


modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath='cnn_conv2D_maxPooling2D.hdf5')


model.fit(x_train, y_train, epochs=256, batch_size=128,
                    validation_split=0.2,
                    callbacks=[earlyStopping, modelCheckPoint],
                    verbose=1)

model.save(path+'cnn_conv2D_maxPooling2D_save_model.h5')


# 4. evaluate and predict
result = model.evaluate(x_test, y_test)
print("loss: ", result[0])
print("acc: ", result[1])



'''
Result
loss:  0.049012500792741776
acc:  0.9872999787330627

'''

 

⭐ Conv2D와 MaxPooling2D 차이

from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D


# 1. data
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# CNN Conv2D 처리하기 위해 4D(Tensor)화
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)


# 2. Model
model = Sequential()
model.add(Conv2D(filters=128,
                 kernel_size=(3, 3),
		 padding='same',
                 strides=1,
                 input_shape=(28, 28, 1),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(5, 5)))
model.summary()
'''
Model: "sequential()"
______________________________________
 Layer (type)      Output Shape
======================================
(Conv2D)           (None, 26, 26, 128) -> stride: defualt=1, 자르고 난 나머지 연산 대상에 포함
(MaxPooling2D)     (None, 5, 5, 128)   -> stride: default=kernel_size(겹치지 않게 진행), 자르고 난 나머지 연산 대상에 미포함

'''

1. 잔여 Data 처리

2. Strides Default

 

CNN → DNN

1. reshape → DNN

# dnn_with_cnn_data1.py

import numpy as np

from tensorflow.keras.datasets import mnist, cifar10, cifar100, fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

path = './_save/'


# 1. data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
'''
x_train.shape: (60000, 784), x_train.shape: (60000,)
x_test.shape: (10000, 784), x_test.shape: (10000,)
'''

# DNN Model을 위한 작업
# Flatten이 아닌 reshape을 통해서 2차원으로 변경
x_train = x_train.reshape(60000, 28*28) 
x_test = x_test.reshape(10000, 28*28)

x_train=x_train/255.
x_test=x_test/255.


# 2. Model
model = Sequential()
model.add(Dense(128, activation='relu', input_shape=(784,)))
model.add(Dropout(0.3))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(32, activation='linear'))
model.add(Dense(10, activation='softmax'))
model.summary()


# 3. Compile and train
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)

modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath='dnn_with_cnn_data1_MCP.hdf5')

model.fit(x_train, y_train, epochs=256, batch_size=32,
                    validation_split=0.2,
                    callbacks=[earlyStopping, modelCheckPoint],
                    verbose=1)

model.save(path+'dnn_with_cnn_data1_save_model.h5')


# 4. evaluate and predict
result = model.evaluate(x_test, y_test)
print("loss: ", result[0])
print("acc: ", result[1])



'''
Result(CNN)
loss:  0.16121244430541992
acc:  0.9692999720573425

Result(DNN)
loss:  0.08280020207166672
acc:  0.9758999943733215

'''

 

2. Flatten

# dnn_with_cnn_data2.py

import numpy as np

from tensorflow.keras.datasets import mnist, cifar10, cifar100, fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

path = './_save/'


# 1. data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
'''
x_train.shape: (60000, 28, 28), x_train.shape: (60000,)
x_test.shape: (10000, 28, 28), x_test.shape: (10000,)
'''

x_train=x_train/255.
x_test=x_test/255.


# 2. Model
model = Sequential()
model.add(Flatten()) # 모델 초반부에 Flatten을 통한 1차원 배열로 변환 input_dim=28*28*1=784 (column)
# 차원: []의 개수
model.add(Dense(128, activation='relu', input_shape=(784,)))
model.add(Dropout(0.3))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(32, activation='linear'))
model.add(Dense(10, activation='softmax'))


# 3. Compile and train
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)

modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath='dnn_with_cnn_data2_MCP.hdf5')

model.fit(x_train, y_train, epochs=256, batch_size=32,
                    validation_split=0.2,
                    callbacks=[earlyStopping, modelCheckPoint],
                    verbose=1)

model.save(path+'dnn_with_cnn_data2_save_model.h5')


# 4. evaluate and predict
result = model.evaluate(x_test, y_test)
print("loss: ", result[0])
print("acc: ", result[1])



'''
Result(CNN)
loss:  0.16121244430541992
acc:  0.9692999720573425

Result(DNN)
loss:  0.08222146332263947
acc:  0.977400004863739

'''

 

3. Dense → Flatten

# dnn_with_dnn_data3.py

import numpy as np

from tensorflow.keras.datasets import mnist, cifar10, cifar100, fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D # 2D: 이미지
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

path = './_save/'


# 1. data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
'''
x_train.shape: (60000, 28, 28), x_train.shape: (60000,)
x_test.shape: (10000, 28, 28), x_test.shape: (10000,)
'''

x_train=x_train/255.
x_test=x_test/255.


# 2. Model
model = Sequential()
model.add(Dense(128, activation='relu', input_shape=(28,28)))
# (data_num, 28), input_dim=28
model.add(Dropout(0.3))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(32, activation='linear'))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
model.summary()
'''
# Dense Model은 2차원 이상을 input으로 받는 것이 가능

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 dense (Dense)               (None, 28, 128)           3712
                            # output_layer = conv2D filter
 dense_1 (Dense)             (None, 28, 64)            8256

 dense_2 (Dense)             (None, 28, 32)            2080

 flatten (Flatten)           (None, 896)               0

 dense_3 (Dense)             (None, 10)                8970

=================================================================
Total params: 23,018
Trainable params: 23,018
Non-trainable params: 0
_________________________________________________________________
'''


# 3. Compile and train
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)

modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath='dnn_with_cnn_data3_MCP.hdf5')


model.fit(x_train, y_train, epochs=256, batch_size=32,
                    validation_split=0.2,

    callbacks=[earlyStopping, modelCheckPoint],
                    verbose=1)

model.save(path+'dnn_with_cnn_data3_save_model.h5')


# 4. evaluate and predict
result = model.evaluate(x_test, y_test)
print("loss: ", result[0])
print("acc: ", result[1])



'''
Result(CNN)
loss:  0.16121244430541992
acc:  0.9692999720573425

Result(DNN)
loss:  0.10574663430452347
acc:  0.9707000255584717

'''

 

➕ CNN Functional Model

# functional_model_with_cnn.py

import numpy as np

from tensorflow.keras.datasets import mnist, cifar10, cifar100, fashion_mnist
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D, Input
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

path = './_save/'


# 1. data
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# print(x_train.shape, y_train.shape) # (60000, 28, 28) (60000,)

x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)

x_train=x_train/255.
x_test=x_test/255.


# 2. Model
input1 = Input(shape=(28,28,1))
dense1 = Conv2D(filters=128,
                 kernel_size=(3, 3),
                 padding='same',
                 strides=1,
                 input_shape=(28, 28, 1),
                 activation='relu')(input1)
dense2 = MaxPooling2D()(dense1)
dense3 = Conv2D(filters=64,
                 kernel_size=(3, 3),
                 padding='same')(dense2)
dense4 = MaxPooling2D()(dense3)
dense5 = Conv2D(filters=32,
                 kernel_size=(3, 3),
                 padding='same')(dense4)
dense6 = Flatten()(dense5)
dense7 = Dense(32, activation='relu')(dense6)
output1 = Dense(10, activation='softmax')(dense7)
model = Model(inputs=input1, outputs=output1)
model.summary()


# 3. Compile and train
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)

modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath=path+'functional_model_with_cnn_MCP.hdf5')

model.fit(x_train, y_train, epochs=256, batch_size=64,
                    validation_split=0.2,
                    callbacks=[earlyStopping, modelCheckPoint],
                    verbose=1)

model.save(path+'functional_model_with_cnn_save_model.h5')


# 4. evaluate and predict
result = model.evaluate(x_test, y_test)
print("loss: ", result[0])
print("acc: ", result[1])



'''
Result
loss:  0.2593150734901428
acc:  0.9047999978065491

'''

 

DNN 데이터의 CNN 처리

# dnn_with_cnn_data_kaggle_bike.py

import pandas as pd
import numpy as np

from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Dense, Input, Dropout, Conv2D, Flatten, MaxPooling2D
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import mean_squared_error, r2_score

path2 = './_save/'


# 1. Data
path = './_data/bike/'
train_csv = pd.read_csv(path+'train.csv', index_col=0)
test_csv = pd.read_csv(path+'test.csv', index_col=0)
submission = pd.read_csv(path+'sampleSubmission.csv', index_col=0)
train_csv = train_csv.dropna()

x = train_csv.drop(['casual', 'registered', 'count'], axis=1)
y = train_csv['count']

x_train, x_test, y_train, y_test = train_test_split(
    x, y,
    shuffle=True,
    train_size=0.7,
    random_state=123
)

# scaler = StandardScaler()
scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
test_csv = scaler.transform(test_csv)

print(x_train.shape, x_test.shape)
print(test_csv.shape) # (6493, 8)


x_train = x_train.reshape(7620, 4, 2, 1)
x_test = x_test.reshape(3266, 4, 2, 1)


# 2. Model(Sequential)
model = Sequential()
model.add(Conv2D(128, (2,2), padding='same', activation='relu', input_shape=(4,2,1)))
model.add(MaxPooling2D(pool_size=(2, 1)))
model.add(Conv2D(64, (2,2), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 1)))
model.add(Conv2D(32, (2,2), padding='same', activation='relu'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1)) # 분류모델이 아니므로 끝이 softmax가 아니어도 됨
model.summary()


'''
# 2. Model(Function)
input1 = Input(shape=(13,))
dense1 = Dense(64, activation='relu')(input1)
drop1 = Dropout(0.3)(dense1)
dense2 = Dense(64, activation='sigmoid')(drop1)
drop2 = Dropout(0.2)(dense2)
dense3 = Dense(32, activation='relu')(drop2)
drop3 = Dropout(0.15)(dense3)
dense4 = Dense(32, activation='linear')(drop3)
output1 = Dense(1, activation='linear')(dense4)
model = Model(inputs=input1, outputs=output1)
model.summary()

summray
node를 random하게 추출하여 훈련을 수행 -> 과적합 문제 해결
summary는 dropout된 node를 나누지 않음
predict 시에는 dropout 사용 X

Total params: 8,225
Trainable params: 8,225
Non-trainable params: 0
'''


# 3. compile and train
model.compile(loss='mse', optimizer='adam', metrics=['mae'])

earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32,
                              restore_best_weights=True,
                              verbose=1)

modelCheckPoint = ModelCheckpoint(monitor='val_loss', mode='auto', verbose=1,
                                   save_best_only=True,
                                   filepath='MCP/keras39_5_kaggle_bike_MCP.hdf5')

model.fit(x_train, y_train,
          epochs=256,
          batch_size=64,
          validation_split=0.2,
          callbacks=[earlyStopping, modelCheckPoint],
          verbose=1)

model.save(path2+'keras39_5_kaggle_bike_save_model.h5') # 가중치 및 모델 세이브


# 4. evaluate and predict
loss = model.evaluate(x_test, y_test)
y_predict = model.predict(x_test)

def RMSE (y_test, y_predict):
    return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE: ", RMSE(y_test, y_predict))

r2 = r2_score(y_test, y_predict)
print("R2: ", r2)

# for submission
test_csv = test_csv.reshape(6493, 4, 2, 1)

y_submit = model.predict(test_csv)
submission['count'] = y_submit
submission.to_csv(path+'sampleSubmission_0126.csv')

'''
Result(DNN)
RMSE:  150.45157752219103
R2:  0.30323941332889803

* 이미지가 아닌 데이터는 CNN이 좋은가 DNN이 좋은가
Result(CNN)
RMSE:  151.84623477201092
R2:  0.2902618673099654

'''

1. Conv2D의 input_shape= 4차원이므로 data의 reshape 필요

x_train.shape(7620, 8) -> x_train.reshape(7620, 4, 2, 1)

데이터 수를 의미하는 7260을 제외한 8을 3차원으로 임의 변경 가능

 

2. input_shape보다 Conv2D(kernel_size), MaxPooling(Pool_size)가 커지지 않도록 shape 확인

model.add(Conv2D(128, (2,2), padding='same', activation='relu', input_shape=(4,2,1)))

input_shape=(4,2,1) -> 4*2 크기의 이미지, kernel_size=(3,3) 불가

 

3. traing data와 predict data shape 맞추기

traing data를 기준으로 model이 구성되었으므로 predict data shape도 traing data에 맞추기

 

 

 

소스 코드

🔗 HJ0216/TIL

 

참고 자료

📑 CNN Model Contruction

 

728x90