MNIST에 Convolution, Relu, MaxPool, Dropout을 추가해서 Accuracy가 99%까지 올라감

 

import tensorflow.compat.v1 as tf
import numpy as np

mnist = tf.keras.datasets.mnist

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape([-1, 784])
test_images  = test_images.reshape([-1,784])
train_images = train_images / 255.
test_images  = test_images / 255.
print(train_images[0])
#train_labels = train_labels.reshape([-1, 784])
print('train_images.shape : ', train_images.shape)
#from tensorflow.examples.tutorials.mnist import input_data

tf.disable_v2_behavior()

#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)


nb_classes = 10


X = tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-1, 28, 28, 1])
Y = tf.placeholder(tf.float32, [None, nb_classes])

keep_prob = tf.placeholder(tf.float32)

# 3x3 filter, color=1(Gray), # of Filter : 32
W1 = tf.Variable(tf.random_normal([3,3,1,32], stddev=0.01))
L1 = tf.nn.conv2d(X_img, W1, strides=[1,1,1,1], padding='SAME')
# => 입력의 이미지 크기와 같다 'SAME'이므로
# => 출력 이미지는 32개가 된다.

L1 = tf.nn.relu(L1)

#kernel size = 2 x 2
#stride : 2 x 2
L1 = tf.nn.max_pool(L1, ksize=[1,2,2,1],
                    strides=[1,2,2,1], padding='SAME')
L1 = tf.nn.dropout(L1, keep_prob=keep_prob)
#stride가 2x2이므로 28x28 이미지가 14x14가 된다.
'''
Tensor("Conv2D:0", shape=(?,28,28,32), dtype=float32)
Tensor("Relu:0", shape=(?,28,28,32), dtype=float32)
Tensor("MaxPool:0", shape=(?,14,14,32), dtype=float32)
'''
#첫번째 Convolution Layer의 출력 : 14(가로)x14(세로)x32(이미지 갯수 = 필터 수)


#input : (?,14,14, 32) #Filter : 64
W2 = tf.Variable(tf.random_normal([3,3,32, 64], stddev=0.01))
L2 = tf.nn.conv2d(L1, W2, strides=[1,1,1,1], padding='SAME')
#Conv : (?,14,14,64)
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
#Pool : (?,7,7,64)
#Pool : (?,7,7,64)
#L2 = tf.reshape(L2, [-1, 7 * 7 * 64])
L2 = tf.nn.dropout(L2, keep_prob=keep_prob)

'''
Tensor("Conv2D_1:0", shape=(?,14,14,64), dtype=float32)
Tensor("Relu_1:0", shape=(?,14,14,64), dtype=float32)
Tensor("MaxPool_1:0", shape=(?,7,7,64), dtype=float32)
Tensor("Reshape_1:0", shape=(?,3136), dtype=float32)
'''

W3 = tf.Variable(tf.random_normal([3,3,64, 128], stddev=0.01))
L3 = tf.nn.conv2d(L2, W3, strides=[1,1,1,1], padding='SAME')
#Conv : (?,14,14,64)
L3 = tf.nn.relu(L3)
L3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
#Pool : (?,7,7,64)
#Pool : (?,7,7,64)
L3 = tf.nn.dropout(L3, keep_prob=keep_prob)
L3 = tf.reshape(L3, [-1, 128 * 4 * 4])

W4 = tf.get_variable("W4", shape=[128*4*4, 625])
b4 = tf.Variable(tf.random_normal([625]))
L4 = tf.nn.relu(tf.matmul(L3, W4) + b4)
L4 = tf.nn.dropout(L4, keep_prob=keep_prob)

W5 = tf.get_variable("W5", shape=[625, 10])
b5 = tf.Variable(tf.random_normal([10]))

#batch_xs, batch_ys = mnist.train.next_batch(100)

hypothesis = tf.nn.softmax(tf.matmul(L4, W5) + b5)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost)

#cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis = 1))
#optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(cost)

prediction = tf.argmax(hypothesis, 1) #예측한 결과를 0~6사이의 값으로 만든다
is_correct = tf.equal(prediction, tf.argmax(Y, 1))#예측한 결과와 Y 데이터를 비교
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) #이것들을 평균낸다

training_epochs = 100
batch_size = 100

import matplotlib.pyplot as plt
import random

#'''
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(train_images.shape[0] / batch_size)

        for i in range(total_batch):
            s_idx = int(train_images.shape[0] * i / total_batch)
            e_idx = int(train_images.shape[0] * (i+1)/ total_batch)
            #print('s_idx : ', s_idx)
            #print('width : ', width)
            batch_xs = train_images[s_idx : e_idx]
            batch_ys = train_labels[s_idx : e_idx]
            #print('batch_xs.shape : ', batch_xs.shape)
            #print('batch_ys.shape : ', batch_ys.shape)
            #Y_one_hot = tf.one_hot(batch_ys, nb_classes)
            Y_one_hot = np.eye(nb_classes)[batch_ys]
            #print('Y_one_hot.shape :', Y_one_hot.shape)
            _,c = sess.run([optimizer, cost], feed_dict={X:batch_xs, Y:Y_one_hot, keep_prob:0.5})
            #print('total_batch : ', total_batch, ', c:', c)
            avg_cost += c / total_batch

        print('Epoch:', '%04d' % (epoch+1), 'cost=', '{:.9f}'.format(avg_cost))
    Y_one_hot = np.eye(nb_classes)[test_labels]
    print("Accuracy : ", accuracy.eval(session=sess, feed_dict={X:test_images, Y:Y_one_hot, keep_prob:1}))
    
    r = random.randint(0, test_images.shape[0] - 1)
    print('label : ', test_labels[r:r+1])
    print('Prediction : ', sess.run(tf.argmax(hypothesis, 1), feed_dict={X:test_images[r:r+1], keep_prob:1}))
    plt.imshow(test_images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
    plt.show()
#'''

2년전인가 수박 겉핡기식으로 겨우겨우 한번 본 영상

 

다 보고 나서 근거 없는 자신감으로 github를 찾아 방황했는데...

 

최근 처음부터 다시 보게 된 강의

 

근데 tensorflow가 2.x로 바뀌면서 강의의 소스가 안 실행이 안되서

(github 소스는 될라나? 확안 해봤음)

 

그래서 나름대로 돌아가게끔 만든 소스를 기록할려고 글을 남김

 

import tensorflow.compat.v1 as tf
import numpy as np

mnist = tf.keras.datasets.mnist

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape([-1, 784])
test_images  = test_images.reshape([-1,784])
train_images = train_images / 255.
test_images  = test_images / 255.
print(train_images[0])
#train_labels = train_labels.reshape([-1, 784])
print('train_images.shape : ', train_images.shape)
#from tensorflow.examples.tutorials.mnist import input_data

tf.disable_v2_behavior()

#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)



nb_classes = 10

X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, nb_classes])

W = tf.Variable(tf.random_normal([784, nb_classes]))
b = tf.Variable(tf.random_normal([nb_classes]))

#batch_xs, batch_ys = mnist.train.next_batch(100)

hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis = 1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(cost)

prediction = tf.argmax(hypothesis, 1) #예측한 결과를 0~6사이의 값으로 만든다
is_correct = tf.equal(prediction, tf.argmax(Y, 1))#예측한 결과와 Y 데이터를 비교
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) #이것들을 평균낸다

training_epochs = 15
batch_size = 100

import matplotlib.pyplot as plt
import random

#'''
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(train_images.shape[0] / batch_size)

        for i in range(total_batch):
            s_idx = int(train_images.shape[0] * i / total_batch)
            e_idx = int(train_images.shape[0] * (i+1)/ total_batch)
            #print('s_idx : ', s_idx)
            #print('width : ', width)
            batch_xs = train_images[s_idx : e_idx]
            batch_ys = train_labels[s_idx : e_idx]
            #print('batch_xs.shape : ', batch_xs.shape)
            #print('batch_ys.shape : ', batch_ys.shape)
            #Y_one_hot = tf.one_hot(batch_ys, nb_classes)
            Y_one_hot = np.eye(nb_classes)[batch_ys]
            #print('Y_one_hot.shape :', Y_one_hot.shape)
            _,c = sess.run([optimizer, cost], feed_dict={X:batch_xs, Y:Y_one_hot})
            #print('total_batch : ', total_batch, ', c:', c)
            avg_cost += c / total_batch

        print('Epoch:', '%04d' % (epoch+1), 'cost=', '{:.9f}'.format(avg_cost))
    Y_one_hot = np.eye(nb_classes)[test_labels]
    print("Accuracy : ", accuracy.eval(session=sess, feed_dict={X:test_images, Y:Y_one_hot}))
    
    r = random.randint(0, test_images.shape[0] - 1)
    print('label : ', test_labels[r:r+1])
    print('Prediction : ', sess.run(tf.argmax(hypothesis, 1), feed_dict={X:test_images[r:r+1]}))
    plt.imshow(test_images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
    plt.show()
#'''

'딥러닝' 카테고리의 다른 글

[KERAS] 학습시 검증데이터 세트 이용 유무  (0) 2021.10.29
다시 실습해 보는 모두의 딥러닝(2) - Lab11(Mnist)  (0) 2021.04.02
Octave 실습정리 4  (0) 2021.03.16
Octave 실습 정리 2  (0) 2021.03.15
Octave 실습 정리 1  (0) 2021.03.15

#  설치 부분 생략(추후 작성)

 

# 데이터 생성 생략(추후 작성) - 다운받은 놈으로 일단 테스트

 

1. ~/jetson-inference/python/training/detection/ssd/data/위치에 다음과 같은 구조의 데이터를 복사한다

[fruit] - [test] - jpg 이미지들
        - [train] - jpg 이미지들
        - [validation] - jpg 이미지들
        - class-descriptions-boxable.csv
        - sub-test-annotations-bbox.csv
        - sub-train-annotations-bbox.csv
        - sub-validation-annotations-bbox.csv
        - test-annotations-bbox.csv
        - train-annotations-bbox.csv
        - validation-annotations-bbox.csv       

 

2. 다음 명령으로 학습한다.

cd ~/jetson-inference/python/training/detection/ssd
python3 train_ssd.py --data=data/fruit --model-dir=models/fruit --batch-size=4 --epochs=30

 

 

 

 

3. 학습이 완료되었으면 model폴더에 생성된 학습 결과를 다음 명령으로 tensorrt 로 변환한다.

python3 onnx_export.py --model-dir=models/fruit

 

4. 테스트 하기 위해서 validation 폴더의 이미지를 다음과 같은 명령으로 일괄적으로 변환해본다. 

detectnet --model=models/fruit/ssd-mobilenet.onnx \
          --labels=models/fruit/labels.txt \
          --input-blob=input_0 --output-cvg=scores --output-bbox=boxes \
          "~/jetson-inference/python/training/detection/ssd/data/fruit/validation/*.jpg"  \
          ~/test_result/fruit_%i.jpg

 

>>> from pymodbus.client.sync import ModbusTcpClient as ModbusClient
>>> import logging
>>> client = ModbusClient('localhost', port=502)
>>> client.connect()
True
>>> rr = client.read_coils(0, 1, unit=1)
>>> print(rr.bits)
[False, False, False, False, False, False, False, False]


>>> rr = client.read_holding_registers(1,18,unit=1)
>>> print(rr.registers)
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> rr = client.read_holding_registers(0,10,unit=1)
>>> print(rr.registers)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
>>> print(rr.registers)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
>>> rr = client.read_holding_registers(0,10,unit=1)
>>> print(rr.registers)
[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]


>>> rq = client.write_register(1,10,unit=1)
>>> rq = client.write_register(2,10,unit=1)
>>> client.close()

 

 

 

 

sudo -H pip install -U jetson-stats

sudo jtop

import jetson.inference
import jetson.utils

net = jetson.inference.detectNet("ssd-mobilenet-v2", [], threshold=0.5)


input = jetson.utils.videoSource('/home/jnx/Downloads/test02.mp4', argv=[])
output = jetson.utils.videoOutput('', argv=[])

ol = "box,labels,conf"

while True:
    img = input.Capture()

    #print('img.width : ', img.width)
    #print('img.height : ', img.height)

    detections = net.Detect(img, overlay=ol)
    output.Render(img)

    output.SetStatus("Object Detection | Network {:.0f} FPS".format(net.GetNetworkFPS()))

    if not input.IsStreaming() or not output.IsStreaming():
        break

www.youtube.com/watch?v=ZK5FYhoJqIg

 

* SSD Device

in video : /dev/nvme0n1p1

my device : /dev/sda1

 

* ~/rootOnNVMe/copy-rootfs-ssd.sh

 > Line 3 : sudo mount /dev/nvme0n1p1 /mnt  => sudo mount /dev/sda1 /mnt 

* ~/rootOnNVMe/data/setssdroot.sh

 >  Line 3 : NVME_DRIVE="/dev/nvme0n1p1" => NVME_DRIVE="/dev/sda1"

 

 

* ~/rootOnNVMe/data/

 > Line 8 : ConditionPathExists=/dev/nvme0n1p1 => ConditionPathExists=/dev/sda1

 

 

 

 

 

'기타' 카테고리의 다른 글

자동차 번호판 학습하기  (1) 2021.04.19
jetson board Performance  (0) 2021.03.25
내 컴퓨터 바이트 오더 확인하기  (0) 2021.03.05
C# Bitmap객체를 8bit gray로 byte array에 담기  (0) 2021.02.05
Jetson TX2(5)  (0) 2020.05.27

 

 

 

* Sin 곡선 그리기

 

* Cos 곡선 그리기

* 2개 이상의 그래프 그리기

* 그래프 저장하려면

cd 'd:\test\';print -dpng 'myPlot.png'

 

* 그래프를 닫으려면

close

* 2개 이상의 그래프를 그리려면

 

* 하나의 윈도우에 두개 이상의 그래프(SubPlot)

* clf(clear fiture) - 화면 지우기

 

 

 

 

 

* 행렬의 크기 및 길이(length)

  - length : 가장 높은 차원의 길이만 구하는 듯

 

* 현재 디렉토리(pwd)

#who 명령 : 메모리 상의 변수
#load 함수 : 데이터 파일을 읽어들임, 변수명은 파일명으로
load('featureX.dat') # featureX 변수에 할당됨
#whos 명령 : 메모리 상의 변수와 상세 정보등을 보여줌(Name, Size, Bytes, Class)
#clear featureX : 메모리상에서 featureX 변수 제거

V = featuresX(1:10) #features 처음 10개의 데이터를 V에 저장
save hello.mat V; #V 변수의 데이터를 hello.mat파일에 저장

clear #모든 변수를 다 지움

load hello.mat #V 변수가 다시 생김

save hello.txt V -ascii #텍스트로 저장



 

 

 

 

 

 

'딥러닝' 카테고리의 다른 글

다시 실습해보는 모두의 딥러닝(1) - Lab7(MNIST)  (0) 2021.04.02
Octave 실습정리 4  (0) 2021.03.16
Octave 실습 정리 1  (0) 2021.03.15
Mnist 학습 후 c#으로 실행하기  (0) 2020.03.10
KERAS - MNIST 소스 분석  (0) 2020.03.06

Coursera 강의 중 실습 내용

 

- Python Numpy 또는 R을 이용하기도 하지만, 문법이 더 투박하다고 하는데 아직까지는 의미를 정확히 이해하지는 못했다.

 

*기본 연산

 

* 논리 연산

  - %는 주석

  - ~= 같지 않다

  - && : AND

  - || : OR

  - xor : XOR

* Prompt 모양 바꾸기

* 변수 선언 및 할당

* 변수 출력

* Matrix 생성

* Vector 생성

* 기타

 

 

 

'딥러닝' 카테고리의 다른 글

Octave 실습정리 4  (0) 2021.03.16
Octave 실습 정리 2  (0) 2021.03.15
Mnist 학습 후 c#으로 실행하기  (0) 2020.03.10
KERAS - MNIST 소스 분석  (0) 2020.03.06
DCGAN 실습  (0) 2020.02.26

+ Recent posts