# mnist를 더욱 정확하게 판단할 수 있도록 여러가지 기법을 써보자
# tensorflow.nn.relu() 함수 더욱정확도가 높은 값을 구할수 있다.
# x가 0보다 크면 기울기가 1인 직선, 0보다 작으면 함수값이 0이된다.
# 이는 0보다 작은 값들에서 뉴런이 죽을 수 있는 단점을 야기한다.
# 또한 sigmoid, tonh 함수보다 학습이 빠르고, 연산 비용이 적고,
# 구현이 매우 간단하는 특징이있다
#최적화 함수도 : AdamOptimizer()
#여기서 소개하는 Adam method는 adagrad + RMSProp의 장점을 섞어놓은 것으로
# 저자가 말하는 Adam method의 주요 장점은 stepsize가 gradient의 resaling에
# 영향을 받지 않는다는 것이다. gradient가 커져도 stepsize는 bound되어 있어서
# 어떠한 objective function을 사용한다 하더라도 안정적으로 최적화를 위한 하강이 가능하다
#Lab 10 MNIST and NN 7장에서의 mnist 결과를 기억하자
import matplotlib.pyplot as plt
import tensorflow as tf
import random
#import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777)
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#more information about the mnist dataset
#parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
#input plave holders
X = tf.placeholder(tf.float32,[None,784])
Y = tf.placeholder(tf.float32,[None,10])
#weights & bias for nn layers 레이어를 여러층 두어서 딥레이어를 구성한다
W1 = tf.Variable(tf.random_normal([784,256])) # 784<==입력 고정 출력256 <==임의대로 설정
b1 = tf.Variable(tf.random_normal([256])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L1 = tf.nn.relu(tf.matmul(X,W1)+b1)
W2 = tf.Variable(tf.random_normal([256,256])) # 앞의 레이어가 256개를 출력하므로 256입력
b2 = tf.Variable(tf.random_normal([256])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L2 = tf.nn.relu(tf.matmul(L1,W2)+b2)
W3 = tf.Variable(tf.random_normal([256,10])) # 784<==입력 고정 출력256 <==임의대로 설정
b3 = tf.Variable(tf.random_normal([10])) #출력이 10 이므로 바이어스 값도 10개가 되야 한다
hypothesis = tf.matmul(L2,W3) + b3
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=hypothesis,labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my mobel
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X:batch_xs,Y:batch_ys}
c,_ = sess.run([cost,optimizer],feed_dict=feed_dict)
avg_cost += c/ total_batch
print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Learning Finished!')
#Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',sess.run(accuracy,feed_dict={
X:mnist.test.images, Y:mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples -1)
print("Label:",sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print("Prediction:",sess.run(
tf.argmax(hypothesis,1), feed_dict={X:mnist.test.images[r:r+1]}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
# Epoch: 0011 cost= 2.250137948
# Epoch: 0012 cost= 1.619561418
# Epoch: 0013 cost= 1.243446105
# Epoch: 0014 cost= 1.036443907
# Epoch: 0015 cost= 0.765386158
# Learning Finished!
# Accuracy: 0.9427 <--- 정확도가 높다
# Label: [5]
# Prediction: [5]
import matplotlib.pyplot as plt
import tensorflow as tf
import random
#import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777)
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#more information about the mnist dataset
#parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
#input plave holders
X = tf.placeholder(tf.float32,[None,784])
Y = tf.placeholder(tf.float32,[None,10])
#weights & bias for nn layers 레이어를 여러층 두어서 딥레이어를 구성한다
W1 = tf.get_variable("W1",shape=[784,256],
initializer=tf.contrib.layers.xavier_initializer()) # xavier_initializer()
b1 = tf.Variable(tf.random_normal([256])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L1 = tf.nn.relu(tf.matmul(X,W1)+b1)
W2 = tf.get_variable("W2",shape=[256,256],
initializer=tf.contrib.layers.xavier_initializer()) # 앞의 레이어가 256개를 출력하므로 256입력
b2 = tf.Variable(tf.random_normal([256])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L2 = tf.nn.relu(tf.matmul(L1,W2)+b2)
W3 = tf.get_variable("W3",shape=[256,10],
initializer=tf.contrib.layers.xavier_initializer()) # 784<==입력 고정 출력256 <==임의대로 설정
b3 = tf.Variable(tf.random_normal([10])) #출력이 10 이므로 바이어스 값도 10개가 되야 한다
hypothesis = tf.matmul(L2,W3) + b3
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=hypothesis,labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my mobel
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X:batch_xs,Y:batch_ys}
c,_ = sess.run([cost,optimizer],feed_dict=feed_dict)
avg_cost += c/ total_batch
print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Learning Finished!')
#Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',sess.run(accuracy,feed_dict={
X:mnist.test.images, Y:mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples -1)
print("Label:",sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print("Prediction:",sess.run(
tf.argmax(hypothesis,1), feed_dict={X:mnist.test.images[r:r+1]}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
'''
Epoch: 0001 cost= 0.300939396 비용의 초기값도 처음부터 매우 낮다
...
Epoch: 0011 cost= 0.012288880
Epoch: 0012 cost= 0.010326613
Epoch: 0013 cost= 0.009648957
Epoch: 0014 cost= 0.010352560
Epoch: 0015 cost= 0.010277308
Learning Finished!
Accuracy: 0.9822 <-- 98%에 달하는 정확도를 보여준다
Label: [9]
Prediction: [9]
'''
import matplotlib.pyplot as plt
import tensorflow as tf
import random
#import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777)
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#more information about the mnist dataset
#parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
#input plave holders
X = tf.placeholder(tf.float32,[None,784])
Y = tf.placeholder(tf.float32,[None,10])
#weights & bias for nn layers 레이어를 여러층 두어서 딥레이어를 구성한다
W1 = tf.get_variable("W1",shape=[784,512],
initializer=tf.contrib.layers.xavier_initializer()) # xavier_initializer()
b1 = tf.Variable(tf.random_normal([512])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L1 = tf.nn.relu(tf.matmul(X,W1)+b1)
W2 = tf.get_variable("W2",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer()) # 앞의 레이어가 256개를 출력하므로 256입력
b2 = tf.Variable(tf.random_normal([512])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L2 = tf.nn.relu(tf.matmul(L1,W2)+b2)
W3 = tf.get_variable("W3",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer()) # 앞의 레이어가 256개를 출력하므로 256입력
b3 = tf.Variable(tf.random_normal([512])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L3 = tf.nn.relu(tf.matmul(L2,W3)+b3)
W4 = tf.get_variable("W4",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer()) # 앞의 레이어가 256개를 출력하므로 256입력
b4 = tf.Variable(tf.random_normal([512])) #출력이 256이므로 바이어스 값도 256개가 되야 한다
L4 = tf.nn.relu(tf.matmul(L3,W4)+b4)
W5 = tf.get_variable("W5",shape=[512,10],
initializer=tf.contrib.layers.xavier_initializer()) # 784<==입력 고정 출력256 <==임의대로 설정
b5 = tf.Variable(tf.random_normal([10])) #출력이 10 이므로 바이어스 값도 10개가 되야 한다
hypothesis = tf.matmul(L4,W5) + b5
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=hypothesis,labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my mobel
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X:batch_xs,Y:batch_ys}
c,_ = sess.run([cost,optimizer],feed_dict=feed_dict)
avg_cost += c/ total_batch
print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Learning Finished!')
#Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',sess.run(accuracy,feed_dict={
X:mnist.test.images, Y:mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples -1)
print("Label:",sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print("Prediction:",sess.run(
tf.argmax(hypothesis,1), feed_dict={X:mnist.test.images[r:r+1]}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
'''
Epoch: 0015 cost= 0.014418301
Learning Finished!
Accuracy: 0.9811 오버피팅으로 인한 결과가 더 후퇴하거나 비슷하게된다.
Label: [1]
Prediction: [1]
과적합은 기계학습에서 학습데이타를 과하게 학습하는 것을 뜻한다.
일반적으로 학습데이터는
과적합 줄이는 방법
1. 데이터의 양을 늘린다.
2. 도멛ㄹ의 복잡고
'''
#드롭아웃을 통한 과적합 해결
# 쉽게 말해서 대충대충 학습을 시키는 것이다
# 손글씨 판별하기
import matplotlib.pyplot as plt
import tensorflow as tf
import random
#import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777)
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#more information about the mnist dataset
#parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
#input plave holders
X = tf.placeholder(tf.float32,[None,784])
Y = tf.placeholder(tf.float32,[None,10])
# dropout (keep_prob) rate 0.7 on training, but should be 1 for testing
keep_prob = tf.placeholder(tf.float32) # 연습시에는 0.5~0.7 정도, 테스팅시는 반드시 1 이다.
# weifhts & bias for nn layers
W1 = tf.get_variable("W1",shape=[784,512],
initializer=tf.contrib.layers.xavier_initializer()) # xavier_initializer()
b1 = tf.Variable(tf.random_normal([512]))
L1 = tf.nn.relu(tf.matmul(X,W1)+b1)
L1 - tf.nn.dropout(L1,keep_prob=keep_prob) # <--- 드롭아웃을 적용하는 부분을 잘보자
W2 = tf.get_variable("W2",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.Variable(tf.random_normal([512]))
L2 = tf.nn.relu(tf.matmul(L1,W2)+b2)
L2 - tf.nn.dropout(L2,keep_prob=keep_prob) # <--- 드롭아웃을 적용하는 부분을 잘보자
W3 = tf.get_variable("W3",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.Variable(tf.random_normal([512]))
L3 = tf.nn.relu(tf.matmul(L2,W3)+b3)
L3 - tf.nn.dropout(L3,keep_prob=keep_prob) # <--- 드롭아웃을 적용하는 부분을 잘보자
W4 = tf.get_variable("W4",shape=[512,512],
initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([512]))
L4 = tf.nn.relu(tf.matmul(L3,W4)+b4)
L4 - tf.nn.dropout(L4,keep_prob=keep_prob) # <--- 드롭아웃을 적용하는 부분을 잘보자
W5 = tf.get_variable("W5",shape=[512,10],
initializer=tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
hypothesis = tf.matmul(L4,W5) + b5
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=hypothesis,labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my mobel
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X:batch_xs,Y:batch_ys, keep_prob: 0.7}
c,_ = sess.run([cost,optimizer],feed_dict=feed_dict)
avg_cost += c/ total_batch
print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Learning Finished!')
#Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',sess.run(accuracy,feed_dict={
X:mnist.test.images, Y:mnist.test.labels,keep_prob: 1}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples -1)
print("Label:",sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print("Prediction:",sess.run(
tf.argmax(hypothesis,1), feed_dict={X:mnist.test.images[r:r+1],keep_prob: 0.7}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
'''
Epoch: 0014 cost= 0.015600037
Epoch: 0015 cost= 0.017687680
Learning Finished!
Accuracy: 0.978 ???왜떨어지지
Label: [9]
Prediction: [9]
'''
# 정확도 99%를 위한 도전 CNN() 합성곱 신경망
# Convolutional Neural Network : CNN
'''
cnn 특징 : 한줄로 입력되는 fully Connected layer 는 1차원 데이터 형태로 한정된다.
하지만 사진(컬러) 3차원을 1차원으로 평면화 시킨다. 이과정에서 정보의 손실이 일어난다
이미지 공간의 공간정보를 유지 상태로 학습이 가능한 모델이 없을까?
====> CNN이 그렇게 할 수 있다.
cnn 용어 :
1. 합성곱 : 이미지에 필터를 합성곱하여 그 결과를 합친것
2. 채널 : 이미지 색상이 컬러이면 RGB 3개의 채널, 흑백이면 1개 채널
3. 필터 : 합성곱을 하기위한 특정한 매트릭스처럼 생긴 필터
4. 커널 : 필터와 동일의미
5. 스트라이드 : 이미지에 합성곱을 할때 필터 몇칸이 이동하는가?
6. 특정맵 : 합성곱을 하여 얻어진 결과를 합하여 하나의 맵으로 작성한것
'''
import matplotlib.pyplot as plt
import tensorflow as tf
import random
#import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777)
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
# Check out http://www.tensorflow.org/get_stared/mnist/beginners for
# more information about the mnist dataset
# hyper parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
#input place holders
X = tf.placeholder(tf.float32,[None,784])
# tf.reshape 텐서의 엘리먼트(element)는 그대로 유지하면서 텐서의 구조를 바꿉니다
# 두번째와 세번쨰 차원은 이미지의 넓이와 높이이고 마지막 파라미터는 이미지의
# 컬러 채널로 여기서는 1(역주: 흑백 이미지이믈) 입니다.
X_img = tf.reshape(X,[-1,28,28,1])
Y = tf.placeholder(tf.float32,[None,10])
# 전체적으로 보면 뉴럴 네트워크 nn가 적용된것임
# L1 imgIn shape=(?,28,28,1)
W1 = tf.Variable(tf.random_normal([3,3,1,32],stddev=0.01))
# Conv ->(?,28,28,32)
# Pool ->(?,14,14,32)
# 컨볼루션
L1 = tf.nn.conv2d(X_img,W1,strides=[1,1,1,1],padding='SAME')
# 리루 적용
L1 = tf.nn.relu(L1)
# 맥스 플링 작업
L1=tf.nn.max_pool(L1,ksize=[1,2,2,1],
strides=[1,2,2,1],padding='SAME')
# 2 * 2 stride는 이미지 사이즈 14*14 로 줄인다
# L@ ImgIn shape=(?,14,14,32)
W2 = tf.Variable(tf.random_normal([3,3,32,64],stddev=0.01))
# 필터크기 33,32 이미지소스, 64개 필터
# Conv -> (?,14,14,64)
# Pool -> (?,7,7,64)
# strides 1칸씩 이동시는 padding='SAME' 이면 입력 이미지와 같은 크기 출력
# strides 2칸씩 이동시는 padding='SAME' 이면 입력 이미지와 절반 크기 출력
L2 =tf.nn.conv2d(L1,W2, strides=[1,1,1,1],padding='SAME') # 스트라이드가 1*1
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') # 스크라이드가 2*2 이므로
L2_flat = tf.reshape(L2,[-1,7*7*64]) # 최종 플리커넥티드로 입력할 3136개 결과를 출력한다
'''
Tensor("Conx2D_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)
'''
# Final FC 7*7*64 inputs -> 10 outputs ------3136입력은 10개의 선택결과로 출력된다.
W3 =tf.get_variable("W3",shape=[7*7*64, 10], initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(L2_flat,W3)+b
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my mobel
print('Learning stared.It takes sometime.')
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size) # 나누어 샘플링 학습을 시킴
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X:batch_xs,Y:batch_ys}
c,_ = sess.run([cost,optimizer],feed_dict=feed_dict)
avg_cost += c/ total_batch
print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Learning Finished!')
#Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(logits,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',sess.run(accuracy,feed_dict={
X:mnist.test.images, Y:mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples -1)
print("Label:",sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print("Prediction:",sess.run(
tf.argmax(logits,1), feed_dict={X:mnist.test.images[r:r+1]}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
'''
Epoch: 0013 cost= 0.016959655
Epoch: 0014 cost= 0.015577860
Epoch: 0015 cost= 0.013503993
Learning Finished!
Accuracy: 0.9884 엄청 오래걸린거치곤..
Label: [0]
Prediction: [0]
'''