You are on page 1of 35

<텐서플로우 기초>

*텐서플로 시작: Hello World

-tensorflow inport 하기

>>> import tensorflow as tf #tf라는 별명을 주로 사용

>>> print(tf.__version__) #버전 확인하기

-텐서플로에서 “Hello World” 출력하기

>>> h=tf.constant("Hello")

>>> w=tf.constant(" World")

>>> hw=h+w

>>> print(hw)

Tensor(“add: 0”, shape=(), dtype=string)

>>> sess=tf.Session()

>>> print(sess.run(hw))

b’Hello World’

텐서플로는 먼저 어떤 연산을 할 지 정의한 후, 향후 연산 실행

hw=h+w는 연산을 하는 것이 아니라 그래프를 구성하는 것

-연산그래프

∙ 그래프: 노드(꼭짓점)와 변으로 이루어짐

∙ 노드: 계산수행, 변: 데이터(일반적으로 텐서)의 흐름

∙ 연산 그래프. 의존성
∙ 의존 관계를 파악하여 연산을 분산시키는 장점이 생김

∙ 텐서플로는 우선 (1) 그래프를 만든 후 (2) 실행하는 순서로 진행

∙ 텐서플로를 임포트하면 기본 그래프가 만들어짐

∙ 그래프 만들기 (노드는 tf.<연산자> 메서드로 만든다)

>>> a=tf.constant (5)

>>> b=tf.constant(2)

>>> c=tf.constant(3)

>>> d=tf.multiply(a,b)

>>> e=tf.add(c,b)

>>> f=tf.subtract(d,e)

∙ 일부의 경우 축약형이 존재한다

d=a*b

e=c+b
f=d-e

∙ 축약형 연산자

∙ 그래프를 만든 후, 세션을 만들고 실행

>>> sess=tf.Session() #그래프 시작

>>> outs=sess.run(f) #run 메서드로 계산. 뒤로 추적해 감.

>>> sess.close() #세션이 끝난 후 닫기

>>> print("out={}".format(outs))

out=5

∙ 그래프의 생성과 관리: 임포트할 때 기본 그래프가 만들어짐

∙ Graph() 메서드: 새로운 그래프 생성

>>> g=tf.Graph()
>>> print(tf.get_default_graph()) #기본 그래프가 무엇인지 알려줌

>>> print(g)

∙ 현재 두 개의 그래프가 있다. 연산을 생성하면 기본 그래프에 연결된다.

>>> a=tf.constant(3)

>>> a.graph is g #예약어 사용. 노드. graph 속성

False

>>> a.graph is tf.get_default_graph()

True

∙ with 구문이 끝나면 세션은 자동 종료

∙ 페치: run 메서드의 인자. 리스트 형태도 가능.

>>> with tf.Session() as sess:

>>> outs=sess.run([a,b,c,d,e,f])

>>> print('out={}'.format(outs)) #[5,2,3,10,5,5] 출력

>>> print(type(outs[0])) #numpy.int32

∙ tensorflow는 numpy와 밀접한 관련이 있음

*텐서

∙ 노드: 연산 객체, 변: 텐서 객체

>>> c=tf.constant(4.0)

>>> print(c)

Tensor(“Const: 0”, shape=(), dtype=float32)

∙ 텐서플로 내부에서 “Const:0”이라는 이름으로 처리

∙ 텐서 객체는 name, shape, dtype 같은 속성이 있음, 속성을 지정하지 않으면 자동으로 설정됨

∙ 데이터 타입: dtype으로 지정할 수 있고, 확인할 수 있다.

>>> c=tf.constant(4.0, dtype=tf.float64)

>>> print(c.dtype) #dtype <float>


∙ 형 변환: 다른 데이터 타입 간의 연산은 예외 발생

tf.cast()를 사용해 형 변환

>>> import tensorflow as tf

>>> x=tf.constant([1,2],name='CP', dtype=tf.float32)

>>> print(x)

Tensor("CP:0", shape=(2,), dtype=float32)

>>> print(x.dtype)

<dtype: 'float32'>

>>> x=tf.cast(x, tf.int32)

>>> print(x.dtype)

<dtype: 'int32'>

∙ 텐서 데이터 타입

∙ 텐서: A ijklm… 형태 배열
∙ 텐서의 형태 찾기 (get_shape() 메서드)

>>> import numpy as np

>>> c=tf.constant([[1,2,3],

[4,5,6]])

>>> print(“Phython List input: {}”.format(c.get_shape()))


Phython List input: (2, 3)

∙ 여러 초기화 함수들

∙ tf.InteractiveSession: eval()메서드를 사용하면 세션 객체를 참조하지 않고도 값을 볼 수 있다.

>>> sess=tf.InteractiveSession()

>>> c=tf.linspace(0.0,1,5) #첫 번째는 실수, 마지막은 정수

>>> print(c.eval())

[0. 0.25 0.5 0.75 1. ]

∙ 텐서의 차원 늘리기 tf.expand_dims()와 행렬 곱

>>> A=tf.constant([[1,2],[3,4]])
>>> print(A.get_shape())

(2, 2)

>>> x=tf.constant([3,1])

>>> print(x.get_shape())

(2, )

>>> x=tf.expand_dims(x,1) #차원 1 늘리기

>>> print(x.get_shape())

(2, 1)

>>> B=tf.matmul(A,x) #2x2 행렬과 2x1 행렬의 곱

>>> sess=tf.InteractiveSession()

>>> print("B={}".format(B.eval()))

B=[[ 5]

[13]]

>>> sess.close()

∙ 전치 행렬 만들기 tf.transpose()

∙ 이름: .name 속성을 이용하여 확인 가능

>>> A=tf.constant(3,name='alpha')

>>> B=tf.constant(4)

>>> print(A.name,B.name)
alpha:0 Const_7:0

∙ 이름 스코프: 노드를 그룹화 할 때 이용

>>> A=tf.constant(4)

>>> B=tf.constant(5)

>>> with tf.name_scope("Add"):


>>> C=A+B

>>> print(C.name)
Add_1/add:0

*변수, 플레이스 홀더

∙ 변수: 텐서플로가 값을 변경함

∙ 변수 만들기: tf.Variable() 메서드

∙ 세션에서 변수의 초기화: tf.global_variables_initializer()

>>> init_val=tf.random_normal((1,5),0,1) #random_normal(shape, 평균, 표준편차)

>>> var=tf.Variable(init_val, name='variable')

>>> print("pre run: \n{}".format(var))


pre run:
<tf.Variable 'variable:0' shape=(1, 5) dtype=float32_ref>

>>> init=tf.global_variables_initializer()

>>> with tf.Session() as sess:

>>> sess.run(init) #반드시 필요

>>> post_var=sess.run(var)

>>> print("\npost run: \n{}".format(post_var))

post run:
[[-1.8759531 -0.2734798 0.37946957 0.22723174 0.11488523]]

∙ placeholder: 나중에 값으로 채워질 ‘변수’

∙ 플레이스홀더는 shape 인수를 선택적으로 사용. None을 사용하면 모든 크기의 데이터를 받을


수 있음

∙ 입력은 사전 (아니면 예외 발생), 키는 변수의 이름

∙ 값: 파이썬 스칼라, 스트링, 리스트, numpy ndarray

>>> W=tf.placeholder(tf.float32, shape=(None,2))

>>> x=tf.placeholder(tf.float32, shape=(2,1))


>>> x_data=np.ones((2,1))

>>> W_data=np.ones((10,2))

>>> wx=tf.matmul(W,x)

>>> sess=tf.Session()

>>> outs=sess.run(wx, feed_dict={W:W_data, x:x_data})

#print("{}".format(outs))

[[2.]
[2.]
[2.]
[2.]
[2.]
[2.]
[2.]
[2.]
[2.]
[2.]]
>>> sess.close()

<선형회귀 (linear regression)>

*선형회귀

∙ y=Wx+b의 형태로 가설을 세우고 실제 데이터를 구현하는 좋은 W, b를 찾는 것이 목표

∙ x, y, W, b는 텐서 형태를 갖는다

∙ 좋다 나쁘다의 판단 근거? 비용 함수!

∙ 비용 함수가 최소가 되는 W, b 조합 찾기가 목표

∙ cost 함수 만들어 보기

import numpy as np

def cost(W, b, x_data, y_data):


y_pred=W*x_data+b

return np.mean((y_pred-y_data)**2)

∙ np. mean

>>> import tensorflow as tf

>>> import numpy as np

>>> def cost(W, b, x_data, y_data):

>>> y_pred=W*x_data+b

>>> return np.mean((y_pred-y_data)**2)

#print(cost(10,10,10,10))

10000.0

>>> X=np.array([1,2,3], dtype=np.float32) #독립변수

>>> Y=np.array([3,4,5], dtype=np.float32) #실제 값

>>> W=float(input("W 추정치? "))

>>> b=float(input("b 추정치? "))

>>> print(cost(W,b,X,Y))

∙ 자동으로 W와 b값을 조정할 방법은 없을까?

∙ Gradient descent algorithm

비용함수를 W와 b의 함수로 간주

수학에서의 gradient는 가장 급격하게 증가하는 방향

gradient의 음의 값은 가장 급격하게 감소하는 방향

계속 감소하다보면 (국소) 최솟값으로 가게 된다.


알파가 작으면 변화가 적어서 오래 걸리고, 알파가 크면 최솟값을 찾지 못할 수 있다.

∙ 파이썬 코드 만들어보기

def grad_desc(W, b, alpha, x_data, y_data):

W-=2*alpha*np.mean((W*x_data+b-y_data)*x_data)

b-=2*alpha*np.mean(W*x_data*b-y_data)

return W,b

∙ 실행 부분

W=float(input(“W 처음 예상? ”))

b=float(input(“b 처음 예상? ”))

alpha=float(input(“learning rate? ”)) #0.1, 0.5, 1

for i in range (1, 1001):

W, b=grad_desc(W, b, alpha, X, Y)

if i%100==0:

co=cost(W,b,X,Y)

print(“i={}, W={}, b={}, co={}”.format(i, W, b, co))

∙ 초기 값에 noise를 넣은 데이터 분석하기

numpy.random의 randn 메서드를 사용함


import numpy as np

import numpy.random as rand

def cost(W,b,x_data,y_data):

y_pred=W*x_data+b

return np.mean((y_pred-y_data)**2)

def grad_desc(W,b,alpha,x_data,y_data):

W-=2*alpha*np.mean((W*x_data+b-y_data)*x_data)

b-=2*alpha*np.mean(W*x_data+b-y_data)

return W,b

X=rand.randn(1000)

W0=2.3

b0=-2.0

Y=W0*X+b0+0.01*rand.randn(1000)

alpha=float(input("learning rate? "))

for i in range(1,1001):

W0,b0=grad_desc(W0,b0,alpha,X,Y)

if i%100==0:

co=cost(W0,b0,X,Y)

print("i={}, W={}, b={}, co={}".format(i,W0,b0,co))

*여러 개의 독립 변수
∙ 파이썬 코드

<linear regression: numpy로 구현하기>

import numpy as np

rng=np.random

def loss(W,b,X,Y):
Yhat=np.matmul(X,W)+b

return np.mean((Yhat-Y)**2)

def grad_desc(W,b,alpha,X,Y):

samples=X.shape[0]

Ydiff=np.matmul(X,W)+b-Y

W-=2*alpha*np.matmul(X.T,Ydiff)/samples

b-=2*alpha*np.mean(Ydiff)

return W,b

#데이터가 바뀌면 이 부분이 바뀌면 됨.

X=np.array([1,2,3],dtype=np.float32).reshape((-1,1))

Y=np.array([3,4,5],dtype=np.float32).reshape((-1,1))

#여기까지가 데이터

#W를 n_in X n_out 행렬이 되게 함.

n_in=1

n_out=1

W=rng.randn(n_in,n_out)

b=rng.randn()

alpha=0.1 #0.1, 0.5, 1

for i in range(1,1001):

W,b=grad_desc(W,b,alpha,X,Y)

if i%100==0 :

print(W,b,loss(W,b,X,Y))

<이진 분류, XOR 문제>

-이진 분류란

X=(특성1, 특성2)의 데이터 형태


경계선 찾기가 목표. 즉, W, b 찾기가 목표

-로지스틱 분류: 이론

hypothesis: logistic(or sigmoid) function

Yhat=WX+b, p=1/1+exp(-Yhat), 0<p<1

Yhat>0: p>1/2

Yhat<0: p<1/2

W,b를 자동으로 찾으려면? 비용함수 (정보이론의 교차 엔트로피)

보통 Ytrue는 0혹은 1이고, p는 (0,1)인 수

이 비용함수를 Gradient Descent Optimization을 이용하여 최적화한다.

<xor 문제>
X=np.array([[0,0],[1,0],[0,1],[1,1]],dtype=np.float32)

and_Y=np.array([[0],[0],[0],[1]],dtype=np.float32)

or_Y=np.array([[0],[1],[1],[1]],dtype=np.float32)

xor_Y=np.array([[0],[1],[1],[0],dtype=np.float32])

위 세 가지 경우를 파이썬 코드에 적용하여 풀어보기

xor은 0.5를 극복하기 어려움

xor 문제 해결하기

W1X1+W2X2+W3X1X2+b=0

<이진분류: numpy로 구현하기>

import numpy as np

rng=np.random
def sig(X):

return 1./(1.+np.exp(-X))

def loss(W,b,X,Y):

Yhat=np.matmul(X,W)+b

P=sig(Yhat)

entropy=-Y*np.log(P)-(1-Y)*np.log(1-P)

return np.mean(entropy)

def grad_desc(W,b,alpha,X,Y):

samples=X.shape[0]

Yhat=np.matmul(X,W)+b

diff=sig(Yhat)-Y

W-=alpha*np.matmul(X.T,diff)/samples

b-=alpha*np.mean(diff)

return W,b

def accuracy(Y,Yhat):

diff=np.round(sig(Yhat))-Y

return np.mean(1.-diff**2)

#데이터가 바뀌면 이 부분이 바뀌면 됨.

X=np.array([[0,0],[0,1],[1,0],[1,1]],dtype=np.float32)

Y=np.array([[0],[1],[1],[1]],dtype=np.float32)

#여기까지가 데이터

#W를 n_in X n_out 행렬이 되게 함.

n_in=2

n_out=1

W=rng.randn(n_in,n_out)

b=rng.randn()
alpha=0.1 #0.1, 0.5, 1

for i in range(1,1001):

W,b=grad_desc(W,b,alpha,X,Y)

if i%100==0 :

Yhat=np.matmul(X,W)+b

print(W,b,accuracy(Y,Yhat))

<텐서플로로 구현하기>

*선형회귀

텐서플로가 제공하는 메서드로 문제 풀기

독립변수 X=(x1, …, xk)가 여러 개인 경우

데이터의 개수가 m개라면 X를 mxk 행렬로 만든다.

W=(w1, …, wk) 역시 여러 개의 변수를 갖게 된다.

Yhat은 tf.matmul(X,W)+b가 된다.

텐서플로는 그래프를 먼저 구현해야한다

데이터를 넣을 리스트 설정

>>> n_inout=3 #n=3인 예

>>> n_output=1 # 종속변수가 1개인 경우

>>> X=tf.placeholder(tf.float32, shape=[None, n_input])

>>> Y=tf.placeholder(tf.float32, shape=[None, n_output])

W(weight)와 b(bias)를 변수로 설정

>>> W=tf.Variable(tf.random_normal([n_input, n_output]))

>>> b=tf.Variable(tf.random_normal([n_output]))

가설 설정
>>> Yhat=tf.matmul(X,W)+b

비용함수 정의

>>> cost=tf.reduce_mean(tf.square(Yhat-Y))

#cost=tf.reduce_mean((Yhat-Y)**2) 와 동일한 결과

Gradient descent method 사용하는 방법

>>> optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)

>>> train=optimizer.minimize(cost) #변수들을 업데이트 해줌

실행하기

>>> sess=tf.Session()

>>> sess.run(tf.global_variables_initializer()) #변수 초기화

>>> for j in range(1,1000):

>>> sess.run(train, feed_dict={X:x_train, Y:y_train})

>>> if j%50==0:

>>> print(sess.run([W,b,cost], {X:x_train, Y: y_train}))

''
I Elm

<tensorflow linear regression code> Y -_


wxtb

m=10000

n_input=2#n=3인예

n_output=1#종속변수가 1개인경우

#가상 데이터 만들기

x_train=rand.randn(m,n_input)

W0=rand.randn(n_input,n_output)
b0=2

y_train=np.matmul(x_train,W0)+b0

X=tf.placeholder(tf.float32,shape=[None,n_input])

Y=tf.placeholder(tf.float32,shape=[None,n_output])


W=tf.Variable(tf.random_normal([n_input,n_output]))

b=tf.Variable(tf.random_normal([n_output]))

: Yhat=tf.matmul(X,W)+b

cost=tf.reduce_mean(tf.square(Yhat-Y))

optimizer =tf.train.GradientDescentOptimizer(learning_rate=0.1)

train=optimizer.minimize(cost)

sess=tf.Session()

sess.run(tf.global_variables_initializer()) #변수초기화!

for j inrange(1,1001):

sess.run(train,feed_dict={X:x_train,Y:y_train})

if j%500==0:

print(sess.run([W,b,cost],{X:x_train,Y:y_train}))

sess.close()

print(W0,b0)

*이진분류

텐서플로에는 tf.sigmoid 메서드가 정의되어 있다

>>> import tensorflow as tf

>>> n_input=3

>>> n_output=1

>>> X=tf.placeholder(tf.float32, shape=(None,n_input))

>>> Y=tf.placeholder(tf.float32, shape=(None, output))


>>> W=tf.Variable(tf.zeros((n,input,n_output)), name='weight')

>>> b=tf.Variable(0.0, name='bias')

>>> Yhat=tf.matmul(X,W)+b

>>> htpothesis=tf.sigmoid(Yhat)

#정밀도 계산

>>> fail_rate=tf.reduce_mean((tf.round(hypothesis)-Y)**2)

reduce_mean(x)는 변수 x가 가리키는 배열 전체 원소의 합을 원소 개수로 나누어 계산

reduce_mean(x, 0)은 열 단위로 평균

reduce_mean(x,1)은 행 단위로 평균

-비용함수 (교차 엔트로피)

cost=tf.reduce_mean(-Y*tf.log(hypothesis))-(1.-Y)*tf.log(1.-hypothesis))

-sigmoid 함수와 교차 엔트로피를 한 번에 계산하는 함수가 정의되어 있다.

tf.nn.sigmoid_cross_entropy_with_logits(labels=, logits=)

*and, or, xor

<tensorflow layer: xor>

x_train=np.array([[0,0],[1,0],[0,1],[1,1]])

y_train=np.array([[0],[1],[1],[0]])

Y = tf.placeholder(tf.float32,[None,1])

X1 = tf.placeholder(tf.float32,[None,2])

W1 = tf.Variable(tf.truncated_normal([2,5]))

b1 = tf.Variable(tf.truncated_normal([5]))

Y1 = tf.matmul(X1,W1)+b1

X2 = tf.sigmoid(Y1)
W2 = tf.Variable(tf.truncated_normal([5,1]))

b2 = tf.Variable(tf.truncated_normal([1]))

Yhat=tf.matmul(X2,W2)+b2

hypothesis=tf.sigmoid(Yhat)

cost=tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=Y,logits=Yhat))

train=tf.train.GradientDescentOptimizer(1).minimize(cost)

feed_dict={X1:x_train,Y:y_train}

accuracy= 1. - tf.reduce_mean((tf.round(hypothesis)-Y)**2)

with tf.Session() as sess:

sess.run(tf.global_variables_initializer()) #변수초기화!

for j inrange(1,101):

sess.run(train,feed_dict)

if j%5==0:

print(sess.run([W1,b1,accuracy],feed_dict))

xor문제를 해결하기 위하여 hidden layer 도입

f2는 비선형 함수, f는 sigmoid 함수

중간에 비선형 함수가 없으면 hidden layer는 의미가 없다


<소프트맥스>

*소프트맥스 분류: 이론

분류할 항목이 여러 개 있는 경우 해당

2진 분류를 여러 번 행하는 것으로 생각할 수 있음

이를 행렬을 이용하여 한 번에 처리

입력의 데이터 수: n_input

출력의 데이터 수: n_output

샘플의 수: Nsample

X, Y, W, b의 형태

X=tf.placeholder(tf.float32, shape=[None, n_input])

Y= tf.placeholder(tf.float32, shape=[None, n_output])

W=tf.Variable(tf.random_normal([n_input, n_output]))

b=tf.Variable(tf.random_normal([n_output]))

Yhat 비용함수 (소프트맥스 사용을 위한 함수임)


argmax 메서드를 이용하여 최댓값의 인덱스 찾기

argmax의 두번째 인자는 축

<tensorflow softmax>

n_input=2

n_output=3

Nsample=10000

# 가상데이터만들기

x_train=rand.randn(Nsample,n_input)

W0=np.array([[0.3,1,0],[0,0.1,0.2]]) #2X3 (n_input X n_output) matrix

b0=np.array([-1,0.5,0]) # 1X3

wxb = np.matmul(x_train,W_train)+b_train #N X n_output matrix

prob = np.exp(wxb) #N X n_output matrix

# 가상데이터 one hot 형태로만들기

y_argmax=np.argmax(prob,axis=1)

y_train=np.zeros((Nsample,n_output))

for i inrange(Nsample):

np.put(y_train[i],y_argmax[i],1)

#Graph construction

X = tf.placeholder(tf.float32,shape=(None,n_input))

Y = tf.placeholder(tf.float32,shape=(None,n_output))

W=tf.Variable(tf.zeros((n_input,n_output)))

b=tf.Variable(tf.zeros((1,n_output)))

Y_hat=tf.matmul(X,W)+b
hypothesis=tf.nn.softmax(Y_hat)

check=tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))

accuracy=tf.reduce_mean(tf.cast(check,dtype=tf.float32))

cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y,logits=Y_hat))

train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

feed_dict={X:x_train,Y:y_train}

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())

print(sess.run([W,b,cost],feed_dict))

for j inrange(1,10001):

sess.run(train,feed_dict)

if j%1000==0: W_val,b_val,loss_val,a=sess.run([W,b,cost,accuracy],feed_dict)

print("no of
iteration={:>4},W={},b={},cost={:>.6e},accuracy={:>.6e}".format( j,W_val,b_val,loss_val,a))

<MNIST data 분석>

*training set, test set

MNIST data: 손글씨

softmax를 이용하여 글씨 인식하기

사이버캠퍼스에서 저장한 파일로부터 데이터 읽어들이기

with np.load(“mnist.npz”) as A:

x_train=A[“x_train”]

x_test=A[“x_test”]

y_train=A[“y_train”]

y_test=A[“y_test”]
28x28=728개의 input data

reshape과 astype을 이용하여 형태와 자료형 변경하기

(re)shape의 -1은 항의 개수를 알아서 정하도록 하기 위함

Y는 0~9까지의 자연수 (10개의 클래스)

Y를 one hot 형태로 변경함

train data는 학습을 위한 데이터

test data는 학습의 결과를 확인하기 위한 데이터

학습을 시킬 때 모든 데이터를 한 번에 학습시키지 않고, 일부를 가지고 학습시킨다 (batch)

import numpy as np

### save와 load : 한 개의 ndarray

np.save(filename,arr,...) # ...은 기타 옵션을 의미함. 필요시 찾아볼 것.

arr=np.arange(10) # 연습용 ndarray

np.save("test1",arr) # directory에 test.npy파일이 생성됨을 확인

b=np.load("test1.npy") #확장자까지 포함한 파일이름 쓰기

print(b)

a1=np.array(["딥","러","닝"]) #한글도 지원됨


np.save("kor",a1)

b=np.load("kor.npy")

print(b)

여러개의 ndarray 저장하기

ndarray에 특별한 이름을 부여하지 않으면 자동으로 arr_0, arr_1의 순서로 이름이 생성됨

압축을 푸는 프로그램으로 npz file을 풀면 각 이름의 파일들이 묶여있음을 알 수 있다.

b.close()

a1=np.arange(10)

a2 = np.linspace(1,2,5)

np.savez("test2",a1,a2)

b=np.load("test2.npz")

print(b)

print(b.files) #어떤 파일들이 있는지 알 수 있다.

ar1=b["arr_0"]

ar2=b["arr_1"]

print(ar1,ar2)

b.close() # npz file을 불러오면 close로 닫아주는 것이 좋다.

여러개의 ndarray 저장하기

ndarray에 이름을 부여하기 위하여 키워드 인자를 사용할 수 있음.

np.savez_compressed("test4",x=a1,y=a2) #압축된 파일은 크기가 준다.

with np.load("test4.npz") as b: #npz file의 경우 with 구문을 쓸 수 있다.

ar1=b["x"]#사전처럼 키워드를 붙여서 ndarray를 저장할 수 있다.


ar2=b["y"]

print(ar1,ar2)

print(b["x"])# with가 끝나면 load된 파일은 자동으로 닫힌다.

#### 텍스트 파일로 저장하기(savetxt), 텍스트 파일 불러오기 (loadtxt)

a=np.zeros((10,3))

np.savetxt("text1.txt",a,delimiter=',')

#구분자를 넣는 경우. 따로 없으면 빈칸

c=np.loadtxt("text1.txt",delimiter=',')

#구분자가 있는 파일 읽어오기.

#구분자를 따로 지정하지 않으면 빈칸으로 구분

print(c)

<mnist_softmax>

import tensorflow as tf

import numpy as np

rng=np.random

mnist.npz file로 부터 데이터 불러들이기

각 글씨를 1차원 배열로 만들기 (reshape method)

자료형은 float32로 하기 (astype method)

with np.load("mnist.npz") as A:

x_train=A["x_train"].reshape((-1,28*28)).astype(np.float32)/255.

y1=A["y_train"]

x_test=A["x_test"].reshape((-1,28*28)).astype(np.float32)/255.
y2=A["y_test"]

#### y를 one hot 형태로 바꾸기

len1=y1.shape[0]

len2=y2.shape[0]

y_train=np.zeros((len1,10),dtype=np.float32)

y_test=np.zeros((len2,10),dtype=np.float32)

for i in range(len1):

y_train[i,y1[i]]=1

for i in range(len2):

y_test[i,y2[i]]=1

그래프 구성하기

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

Y = tf.placeholder(tf.float32, [None, 10])

W = tf.Variable(tf.zeros([784, 10]))

b = tf.Variable(tf.random_normal([10]))

Yhat = tf.matmul(X, W)+b

hypothesis=tf.nn.softmax(Yhat)

correct=tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))

accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=Yhat, labels=Y))

train=tf.train.GradientDescentOptimizer(0.5).minimize(cost)

train data로 학습하기

training_epochs = 15
batch_size = 100

total_batch = x_train.shape[0] // batch_size

sess=tf.Session()

sess.run(tf.global_variables_initializer())

for epoch in range(training_epochs):

for i in range(total_batch):

batch_x = x_train[batch_size*i:batch_size*(i+1),:]

batch_y = y_train[batch_size*i:batch_size*(i+1),:]

sess.run(train,{X:batch_x,Y:batch_y})

print(sess.run(accuracy,{X:x_train,Y:y_train}))

test data로 정확도 확인하기

print(sess.run(accuracy,{X: x_test, Y: y_test}))

import matplotlib.pyplot as plt

%matplotlib inline

for i in range(20):

r = rng.randint(0, len2)

print("Label:", sess.run(tf.argmax(y_test[r:r+1], 1)))

print("Prediction:", sess.run(tf.argmax(hypothesis, 1), feed_dict={X: x_test[r:r + 1]}))

plt.imshow(x_test[r:r + 1].reshape(28, 28), cmap='gray', interpolation='nearest')

plt.show()

<합성곱 신경망(Convolutional Neural Network: CNN)>

*CNN

전체 데이터를 균등하게 분리하여 같은 weight와 bias로 변환

W의 여러 조합을 통하여 하나의 inage에서 특성맵(feature map) 여러 개를 만든다


여러 개의 특성맵을 묶어 convolution layer를 만든다.
<mnist_cnn>

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

%matplotlib inline

rng=np.random

with np.load("mnist.npz") as A:

x_train=A["x_train"].reshape((-1,28,28,1)).astype(np.float32)/255.

y1=A["y_train"]

x_test=A["x_test"].reshape((-1,28,28,1)).astype(np.float32)/255.

y2=A["y_test"]

len1=y1.shape[0]

len2=y2.shape[0]

y_train=np.zeros((len1,10),dtype=np.float32)

y_test=np.zeros((len2,10),dtype=np.float32)

for i in range(len1):

y_train[i,y1[i]]=1

for i in range(len2):

y_test[i,y2[i]]=1

tf.set_random_seed(100)

X = tf.placeholder(tf.float32, [None, 28,28,1])

Y = tf.placeholder(tf.float32, [None, 10])

W1 = tf.Variable(tf.truncated_normal([3, 3, 1, 32], stddev=0.01))

# Conv -> (?, 28, 28, 32)

# Pool -> (?, 14, 14, 32)


L1 = tf.nn.conv2d(X, 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')

W2 = tf.Variable(tf.truncated_normal([3, 3, 32, 64], stddev=0.01))

# Conv ->(?, 14, 14, 64)

# Pool ->(?, 7, 7, 64)

L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')

L2 = tf.nn.relu(L2)

L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')

L2_flat = tf.reshape(L2, [-1, 7 * 7 * 64])

'''

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)

'''

# Final FC 7x7x64 inputs -> 10 outputs

W3 = tf.Variable(tf.truncated_normal([7*7*64,10],stddev=0.01))

b = tf.Variable(tf.random_normal([10]))

Yhat = tf.matmul(L2_flat, W3) + b

correct=tf.equal(tf.argmax(Yhat,1),tf.argmax(Y,1))

accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=Yhat, labels=Y))


train=tf.train.AdamOptimizer(0.001).minimize(cost)

training_epochs = 10

batch_size = 100

total_batch = x_train.shape[0] // batch_size

sess=tf.Session()

sess.run(tf.global_variables_initializer())

print("Now begins: it takes some time.")

for epoch in range(training_epochs):

for i in range(total_batch):

batch_x = x_train[batch_size*i:batch_size*(i+1),:]

batch_y = y_train[batch_size*i:batch_size*(i+1),:]

sess.run(train,{X:batch_x,Y:batch_y})

trc,tra=sess.run([cost,accuracy],{X:x_train,Y:y_train})

print("epoch =",epoch+1)

tec,tea=sess.run([cost,accuracy],{X:x_test,Y:y_test})

print("train cost=",trc," train accuracy=",tra)

print("test cost=",tec," test accuracy=",tea)

com=sess.run(correct,feed_dict={X:x_test,Y:y_test})

i=1

for r in range(10000):

if com[r]==False:

t_label=sess.run(tf.argmax(y_test[r:r+1], 1))

t_pre=sess.run(tf.argmax(Yhat, 1), feed_dict={X: x_test[r:r + 1]})

print("Label=[{}]\nPrediction=[{}]".format(t_label[0],t_pre[0]))

i+=1
plt.imshow(x_test[r:r + 1].reshape(28, 28), cmap='gray', interpolation='nearest')

plt.show()

if i>20:

break

sess.close()

You might also like