donut

'TensorFlow'에 해당되는 글 9건

  1. Python Tensorflow CNN_pooling
  2. Python Tensorflow CNN_basic
  3. DNN_XOR구현
  4. NN_XOR 구현
  5. Logistic_XOR 구현
  6. Tensorflow 다중선형회귀 공부
  7. Python Logistic Regression

Python Tensorflow CNN_pooling

Tensorflow/CNN
CNN_pooling

Python Tensorflow CNN

pooling

지난 포스팅에서 필터를 활용하여 conv2d 레이어층을 만들어 적용시켰었다.
CNN흐름에서 도출된 레이어층을 샘플링(풀링)한다.
풀링의 종류는 평균풀링과 맥스풀링이 존재하며,

maxpooling이 많이 쓰인다.

모듈세팅

In [18]:
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

maxpooling 실습

padding X

In [19]:
#2*2테스트 이미지 생성, image의 텐서의 각 값은 아래와 같음

image = tf.constant([[[[1],[2]],
                    [[6],[4]]]], dtype=np.float32)

#maxpool2D연산을 수행한다
#pool_size2, strides=1, padding X
pool = keras.layers.MaxPool2D(pool_size=(2,2), strides=1, padding='VALID')(image)
print(pool.shape)
print(pool.numpy())
(1, 1, 1, 1)
[[[[6.]]]]

padding O

In [20]:
#2*2테스트 이미지 생성, image의 텐서의 각 값은 아래와 같음

image = tf.constant([[[[1],[2]],
                    [[6],[4]]]], dtype=np.float32)

#maxpool2D연산을 수행한다
#pool_size2, strides=1, padding O
pool = keras.layers.MaxPool2D(pool_size=(2,2), strides=1, padding='SAME')(image)
print(pool.shape)
print(pool.numpy())
(1, 2, 2, 1)
[[[[6.]
   [4.]]

  [[6.]
   [4.]]]]

conv -> pooling 실습

mnist data활용

In [21]:
#mnist데이타 호출
mnist = keras.datasets.mnist
class_names = ['0','1','2','3','4','5','6','7','8','9']

데이타 세팅

In [22]:
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

데이타 확인

In [23]:
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(10000,)
In [24]:
print(train_images[0].shape)
print(train_images)
(28, 28)
[[[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 ...

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]]
In [25]:
img = train_images[0]
plt.imshow(img, cmap='gray')
plt.show()

데이타 정규화

텐서의 값을 0~1사이의 값으로 정규화 시킨다

In [53]:
train_images = train_images.astype(np.float32) / 255.
test_images = test_images.astype(np.float32) / 255.

데이터 확인

정규화를 해도 데이터이미지는 동일하다 train_images의 이미지 1개만 사용함

In [54]:
img = train_images[0]
plt.imshow(img, cmap='gray')
plt.show()
In [55]:
img.shape
Out[55]:
(28, 28)

conv2d레이어 연산

이미지를 4차원으로 변환한 후 작업한다

In [56]:
#4차원으로 변환
#배치size, 세로, 가로, 채널로 4차원으로 만들어 줘야함
#배치size를 -1로 하면, 자동으로 입력이 된다.
#이 경우 이미지 1장만 사용하기 때문에 1로 됨
#채널은 색상 (그레이) 한가지만 사용하기 때문에 1임
img = img.reshape(-1,28,28,1)
print("image.shape, 배치size, 세로, 가로, 채널", img.shape)
img = tf.convert_to_tensor(img)


#필터로 사용하기위해 랜덤값으로 init값 설정
weight_init = keras.initializers.RandomNormal(stddev=0.01)


#필터5개, 커널사이즈(필터사이즈)3*3, strides:2*2, 패딩 사용
conv2d = keras.layers.Conv2D(filters=5, kernel_size=3, strides=(2, 2), padding='SAME', 
                             kernel_initializer=weight_init)(img)


print("conv2d.shape , 배치size, 세로, 가로, 채널 ",conv2d.shape)
feature_maps = np.swapaxes(conv2d, 0, 3)
for i, feature_map in enumerate(feature_maps):
    plt.subplot(1,5,i+1), plt.imshow(feature_map.reshape(14,14), cmap='gray')
plt.show()
image.shape, 배치size, 세로, 가로, 채널 (1, 28, 28, 1)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 14, 14, 5)

pooling layer 연산

In [57]:
#pooling size 2*2
#strides 2
#padding O
#입력값 conv2d
pool = keras.layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='SAME')(conv2d)
print("pool.shape , 배치size, 세로, 가로, 채널", pool.shape)

feature_maps = np.swapaxes(pool, 0, 3)
for i, feature_map in enumerate(feature_maps):
    plt.subplot(1,5,i+1), plt.imshow(feature_map.reshape(7, 7), cmap='gray')
plt.show()
pool.shape , 배치size, 세로, 가로, 채널 (1, 7, 7, 5)

이후 fully Connected layer연산을 진행한다.

pooling가 완료된 레이어를 flat해주고, 출력값을 도출하고 softmax등의 연산을 거치게 된다.

해당 포스팅은 모두를위한 딥러닝과, 부스트코스 강의를 참고하였습니다.

'Tensorflow > CNN' 카테고리의 다른 글

Python Tensorflow CNN_basic  (0) 2020.08.25

Python Tensorflow CNN_basic

Tensorflow/CNN

 

 

 

CNN 기본 원리 실습

파이썬 텐서플로우 CNN 코드 실습.
CNN : 합성곱 신경망(Convolutional Neural Network)
이미지의 특징을 찾아 분류하는데 용이하게 쓰임

모듈 세팅

In [20]:
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
 

실습에 사용할 이미지 준비

In [21]:
#4차원의 텐서 준비
image= tf.constant([[[[1],[2],[3]],
                    [[4],[5],[6]],
                    [[7],[8],[9]]]],dtype = np.float32)
#배치size : 사진의 갯수
#채널 수 : 색상구분 (회색만으로 구분하기 때문에 1)
print("배치size, 세로, 가로, 채널 수",image.shape)
#
plt.imshow(image.numpy().reshape(3,3), cmap='Greys')
plt.show()
 
배치size, 세로, 가로, 채널 수 (1, 3, 3, 1)
 
 

필터, con레이어 설정 패딩 사용x

In [22]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)

#필터로 사용할 weight
#2*2로 이루어져 있고, 각 값이 1로 된 필터임
#세로, 가로, 채널, 갯수
weight = np.array([[[[1.]],[[1.]]],
                   [[[1.]],[[1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)
#init설정
weight_init = tf.constant_initializer(weight)

#con레이어 설정
#필터 1개, 커널사이즈(필터사이즈) 2*2 ->2, 패딩 x(valid), stribe =1(디폴트)

conv2d = keras.layers.Conv2D(filters=1, kernel_size=2, padding='VALID', 
                             kernel_initializer=weight_init)(image)
#배치size, 세로, 가로, 채널 
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
print(conv2d.numpy().reshape(2,2))
plt.imshow(conv2d.numpy().reshape(2,2), cmap='gray')
plt.show

#패딩을 사용하지 않았기 때문에, conv2연산후 가로세로가 줄었다.
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 1)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 2, 2, 1)
[[12. 16.]
 [24. 28.]]
Out[22]:
<function matplotlib.pyplot.show(close=None, block=None)>
 
 

패딩 사용

In [23]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)

#필터로 사용할 weight
#2*2로 이루어져 있고, 각 값이 1로 된 필터임
#세로, 가로, 채널, 갯수
weight = np.array([[[[1.]],[[1.]]],
                   [[[1.]],[[1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)
#init설정
weight_init = tf.constant_initializer(weight)

#con레이어 설정
#필터 1개, 커널사이즈(필터사이즈) 2*2 ->2, 패딩 O(same), stribe =1(디폴트)

conv2d = keras.layers.Conv2D(filters=1, kernel_size=2, padding='SAME', 
                             kernel_initializer=weight_init)(image)
#배치size, 세로, 가로, 채널 
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
print(conv2d.numpy().reshape(3,3))
plt.imshow(conv2d.numpy().reshape(3,3), cmap='gray')
plt.show

#패딩을 사용하지 않았기 때문에, conv2연산후 가로세로가 줄었다.
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 1)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 3, 3, 1)
[[12. 16.  9.]
 [24. 28. 15.]
 [15. 17.  9.]]
Out[23]:
<function matplotlib.pyplot.show(close=None, block=None)>
 
 

필터를 여러개 사용하기

In [25]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)


#필터는 모두 2*2로 이우러져있음
#필터1은 1로만 채워짐
#필터2는 10으로만 채워짐
#필터3은 -1로만 채워짐


weight = np.array([[[[1.,10.,-1.]],[[1.,10.,-1.]]],
                   [[[1.,10.,-1.]],[[1.,10.,-1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)

weight_init = tf.constant_initializer(weight)
conv2d = keras.layers.Conv2D(filters=3, kernel_size=2, padding='SAME',
                             kernel_initializer=weight_init)(image)
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
feature_maps = np.swapaxes(conv2d, 0, 3)
for i, feature_map in enumerate(feature_maps):
    print(feature_map.reshape(3,3))
    plt.subplot(1,3,i+1), plt.imshow(feature_map.reshape(3,3), cmap='gray')

plt.show()
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 3)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 3, 3, 3)
[[12. 16.  9.]
 [24. 28. 15.]
 [15. 17.  9.]]
[[120. 160.  90.]
 [240. 280. 150.]
 [150. 170.  90.]]
[[-12. -16.  -9.]
 [-24. -28. -15.]
 [-15. -17.  -9.]]
 
 

해당 포스팅은 모두를 위한 딥러닝, 부스트코스를 참고하여 작성하였습니다.

In [ ]:
 

'Tensorflow > CNN' 카테고리의 다른 글

Python Tensorflow CNN_pooling  (0) 2020.08.26

DNN_XOR구현

Tensorflow/DNN

 

 

 

DNN(Deep Neural Network)_XOR

이번 포스팅은 XOR알고리즘 구현 3탄입니다.
이미 지난번 포스팅에서 각각 분류함수1회, 분류함수3회를 사용하여 풀이를 해보았었는데요.
이번에는 분류함수 4회를 사용하여 풀이하는 포스팅을 진행하겠습니다.

 

모듈선언

In [23]:
import numpy as np
import tensorflow as tf
tf.random.set_seed(0)
print(tf.__version__)
 
2.1.0
 

XOR데이터 선언

In [24]:
x = [[0, 0],
    [0, 1],
    [1, 0],
    [1, 1]]
y = [[0],
    [1],
    [1],
    [0]]
 

학습시킬 dataset선언

In [25]:
#학습시킬 dataset 준비
dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(len(x))
In [26]:
#데이터 셋 확인
[i for i in dataset]
Out[26]:
[(<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
  array([[0, 0],
         [0, 1],
         [1, 0],
         [1, 1]], dtype=int32)>,
  <tf.Tensor: shape=(4, 1), dtype=int32, numpy=
  array([[0],
         [1],
         [1],
         [0]], dtype=int32)>)]
 

전처리 함수

In [27]:
#형식을 플롯으로 맞춰준다.
#tf.cast는 2가지 사용법이 있다.
#tf.cast('조건') 일경우 참 거짓에 따라 1,0 반환
#그외에는 소수점 이하를 버림 해준다.
def preprocess_data(features, labels):
    features = tf.cast(features, tf.float32)
    labels = tf.cast(labels, tf.float32)
    return features, labels
In [46]:
preprocess_data(x,y)
Out[46]:
(<tf.Tensor: shape=(4, 2), dtype=float32, numpy=
 array([[0., 0.],
        [0., 1.],
        [1., 0.],
        [1., 1.]], dtype=float32)>,
 <tf.Tensor: shape=(4, 1), dtype=float32, numpy=
 array([[0.],
        [1.],
        [1.],
        [0.]], dtype=float32)>)
 

w,b 선언

In [37]:
#총 4번의 분류함수 사용을 위해 W,b를 4개씩 만들어준다.
#이때 메트릭스의 계산이 가능하도록 차원을 잘 설정 해줘야한다.
#ex) (2,1) * (1,1) = (2,1)
#    (3,2) * (2,2) = (3,2)
#xor은 (4,2) 임으로 (2,?)가 곱해져야함
W1 = tf.Variable(tf.random.normal((2, 10)), name='weight1')
b1 = tf.Variable(tf.random.normal((1,)), name='bias1')

W2 = tf.Variable(tf.random.normal((10, 10)), name='weight2')
b2 = tf.Variable(tf.random.normal((1,)), name='bias2')

W3 = tf.Variable(tf.random.normal((10, 10)), name='weight3')
b3 = tf.Variable(tf.random.normal((1,)), name='bias3')

W4 = tf.Variable(tf.random.normal((10, 1)), name='weight4')
b4 = tf.Variable(tf.random.normal((1,)), name='bias4')
 

hypothesis함수

In [38]:
#여러겹의 시그모이드 함수계산을 한다.
def deep_nn(features):
    layer1 = tf.sigmoid(tf.matmul(features, W1) + b1)
    layer2 = tf.sigmoid(tf.matmul(layer1, W2) + b2)
    layer3 = tf.sigmoid(tf.matmul(layer2, W3) + b3)
    hypothesis = tf.sigmoid(tf.matmul(layer3, W4) + b4)
    return hypothesis
In [39]:
#오차율 함수
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(hypothesis) + (1 - labels) * tf.math.log(1 - hypothesis))
    return cost
#정확도 함수
def accuracy_fn(hypothesis, labels):
    predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels), dtype=tf.float32))
    return accuracy
#경사하강법 함수
def grad(hypothesis, features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(deep_nn(features),features,labels)
    return tape.gradient(loss_value, [W1, W2, W3, W4, b1, b2, b3, b4])
In [43]:
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
In [44]:
EPOCHS = 5000

for step in range(EPOCHS+1):
    for features, labels  in dataset:
        features, labels = preprocess_data(features, labels)
        grads = grad(deep_nn(features), features, labels)
        optimizer.apply_gradients(grads_and_vars=zip(grads,[W1, W2, W3,W4, b1, b2, b3, b4]))
        if step % 500 == 0:
            print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(deep_nn(features),features,labels)))
 
Iter: 0, Loss: 0.6387
Iter: 500, Loss: 0.5629
Iter: 1000, Loss: 0.2864
Iter: 1500, Loss: 0.0466
Iter: 2000, Loss: 0.0176
Iter: 2500, Loss: 0.0100
Iter: 3000, Loss: 0.0068
Iter: 3500, Loss: 0.0051
Iter: 4000, Loss: 0.0040
Iter: 4500, Loss: 0.0033
In [51]:
#XOR에 대한 어큐러시 확인
x_data, y_data = preprocess_data(x, y)
test_acc = accuracy_fn(deep_nn(x_data),y_data)
print("Testset Accuracy: {:.4f}".format(test_acc))
 
Testset Accuracy: 1.0000
 

해당 포스팅은 부스트코스와,모두를위한 딥러닝 강의를 참고하여 작성하였습니다.

'Tensorflow > DNN' 카테고리의 다른 글

NN_XOR 구현  (0) 2020.08.08
Logistic_XOR 구현  (0) 2020.08.08

NN_XOR 구현

Tensorflow/DNN

 

 

 

 

NN(Neural Network)_XOR

이번 포스팅은 지난번 XOR문제를 한번의 분류함수로 풀이한 포스팅과 이어지는 내용입니다.

이번에는 여러번의 logistic함수를 중첩해서 문제를 해결하게됩니다.

지난번과 동일한 데이터를 사용합니다.

In [1]:
import numpy as np
import tensorflow as tf

tf.random.set_seed(0)

print(tf.__version__)
 
2.1.0
In [4]:
#XOR데이터를 세팅해준다

x = [[0, 0],
     [0, 1],
     [1, 0],
     [1, 1]]
y = [[0],
     [1],
     [1],
     [0]]
In [5]:
#학습시킬 dataset 준비
dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(len(x))
#전처리를 위한 함수 준비(데이터형식을 맞춰줌)
def preprocess_data(features, labels):
    features = tf.cast(features, tf.float32)
    labels = tf.cast(labels, tf.float32)
    return features, labels
In [6]:
#총 3번의 분류함수 사용을 위해 W,b를 3개씩 만들어준다.

W1 = tf.Variable(tf.random.normal((2, 1)), name='weight1')
b1 = tf.Variable(tf.random.normal((1,)), name='bias1')

W2 = tf.Variable(tf.random.normal((2, 1)), name='weight2')
b2 = tf.Variable(tf.random.normal((1,)), name='bias2')

W3 = tf.Variable(tf.random.normal((2, 1)), name='weight3')
b3 = tf.Variable(tf.random.normal((1,)), name='bias3')
In [7]:
#뉴럴 넷 함수 설정
#총 3번의 시그모이드 함수를 적용시키게됨
#1,2계층에서 사용하여 얻은 시그모이드 값을
#3계층에서 한번더 시그모이드를 적용한다.
def neural_net(features):
    layer1 = tf.sigmoid(tf.matmul(features, W1) + b1)
    layer2 = tf.sigmoid(tf.matmul(features, W2) + b2)
    layer3 = tf.concat([layer1, layer2],-1)
    layer3 = tf.reshape(layer3, shape = [-1,2])
    hypothesis = tf.sigmoid(tf.matmul(layer3, W3) + b3)
    return hypothesis
In [8]:
#오차율, 정확도, 경사하강법 함수 설정
def loss_fn(hypothesis, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(hypothesis) + (1 - labels) * tf.math.log(1 - hypothesis))
    return cost

optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)

def accuracy_fn(hypothesis, labels):
    predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels), dtype=tf.float32))
    return accuracy

def grad(hypothesis, features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(neural_net(features),labels)
    return tape.gradient(loss_value, [W1, W2, W3, b1, b2, b3])
In [9]:
#지난번 1회의 분류함수로 적용했을땐
#loss가 감소하지않고 일정했는데
#뉴럴넷, 즉 계층 별 계산을 통해 로스가 감소하는걸 확인 가능했다.
EPOCHS = 5000

for step in range(EPOCHS):
    for features, labels  in dataset:
        features, labels = preprocess_data(features, labels)
        grads = grad(neural_net(features), features, labels)
        optimizer.apply_gradients(grads_and_vars=zip(grads,[W1, W2, W3, b1, b2, b3]))
        if step % 500 == 0:
            print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(neural_net(features),labels)))
 
Iter: 0, Loss: 1.0160
Iter: 500, Loss: 0.6482
Iter: 1000, Loss: 0.5609
Iter: 1500, Loss: 0.4236
Iter: 2000, Loss: 0.2926
Iter: 2500, Loss: 0.2021
Iter: 3000, Loss: 0.1465
Iter: 3500, Loss: 0.1120
Iter: 4000, Loss: 0.0895
Iter: 4500, Loss: 0.0739
 

해당포스팅은 부스트코스 강의와, 모두를위한 딥러닝 강의를 참고하였습니다.

In [ ]:
 

'Tensorflow > DNN' 카테고리의 다른 글

DNN_XOR구현  (0) 2020.08.12
Logistic_XOR 구현  (0) 2020.08.08

Logistic_XOR 구현

Tensorflow/DNN

 

 

 

 

NN(Neural Network)_XOR

NN(인공신경망)을 통해 컴퓨터가 사람의 뇌처럼
복잡한 계산을 할 수있게 한다.

대표적으로 XOR 알고리즘이 그 예다.
XOR은 아래 처럼, 주어진 두 수가 같은 경우에 1, 다를경우는 0을 출력한다. 즉 OR과 반대다.

XOR알고리즘을 풀기위해선 여러번의 여러번의 계산이 필요하다.
분류 함수로 한번에 할 수 없고, 분류 함수를 단계별로 진행해야 풀이가 가능하다.

이번 포스팅에서는 한번의 분류함수로 xor을 풀이해 보겠습니다.

In [3]:
x = [[0, 0],
     [0, 1],
     [1, 0],
     [1, 1]]
y = [[0],
     [1],
     [1],
     [0]]
 

XOR알고리즘을 tf코드로 모델 만들기

In [4]:
import numpy as np
import tensorflow as tf
print(tf.__version__)
 
2.1.0
In [5]:
#학습시킬 dataset 세팅
#배치값 미지정
dataset= tf.data.Dataset.from_tensor_slices((x,y))
In [6]:
#dataset값 확인
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 0], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([0], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 1], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([1], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 0], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([1], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 1], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([0], dtype=int32)>)]
4
In [7]:
#학습시킬 dataset 세팅
#배치값 x의 길이로 설정
#배치는 한번에 학습시킬 size임
dataset= tf.data.Dataset.from_tensor_slices((x,y)).batch(len(x))
In [8]:
#dataset값 확인
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]], dtype=int32)>, <tf.Tensor: shape=(4, 1), dtype=int32, numpy=
array([[0],
       [1],
       [1],
       [0]], dtype=int32)>)]
1
 

전처리 함수(데이터 타입 맞추기)

In [10]:
def preprocess_data(features, labels):
    features = tf.cast(features, tf.float32)
    labels = tf.cast(labels, tf.float32)
    return features, labels
 

W, b 설정

In [11]:
#W,b의 초기값은 0이나 랜덤으로 으로 정해주면된다
#W = tf.Variable(tf.random.normal((2,1)))
#b = tf.Variable(tf.random.normal((1,)))
W = tf.Variable(tf.zeros((2,1)), name= 'weight')
b = tf.Variable(tf.zeros((1,)), name= 'bias')
print(W.numpy(), b.numpy())
 
[[0.]
 [0.]] [0.]
 

시그모이드 선언

In [12]:
def logistic_regression(features):
    hypothesis = tf.divide(1., 1. + tf.exp(tf.matmul(features, W) + b))
    return hypothesis
 

코스트 함수 선언

In [13]:
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(logistic_regression(features)) + (1-labels) * tf.math.log(1-hypothesis))
    return cost
#러닝레이트도 함께 선언
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
 

결과값 도출 함수 구현

시그모이드 함수로 도출된 hypothesis를 0 or 1로 cast해준다.

tf.cast => 조건이 참일경우 1, 거짓일 경우 0출력
tf.equal => 주어인 값이 같은경우 True, 다를경우 False
아래는 cast와 equal를 이해하기 쉽도록 예시를 작성 하였습니다.

In [14]:
test1 = 0.3
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[14]:
0.0
In [15]:
test1 = 0.6
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[15]:
1.0
In [16]:
test1 = 0.6
test2 = 0.6
test3 = tf.equal(test1,test2)
test3.numpy()
Out[16]:
True
In [17]:
test7 = tf.cast(tf.equal(test1,test2),dtype = tf.float32)
test7.numpy()
Out[17]:
1.0
In [18]:
def accuracy_fn(hypothesis, labels):
    predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels), dtype=tf.float32))
    return accuracy
 

경사하강법

In [19]:
def grad(hypothesis, features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(logistic_regression(features),features,labels)
    return tape.gradient(loss_value, [W,b])
 

실행

로지스틱 함수로 xor알고리즘을 완벽하게 구현하지 못했다.
loss값이 더이상 감소하지 않는 것을 확인 할 수 있었다.

In [23]:
EPOCHS = 1001

for step in range(EPOCHS):
    for features, labels  in dataset:
        features, labels = preprocess_data(features, labels)
        grads = grad(logistic_regression(features), features, labels)
        optimizer.apply_gradients(grads_and_vars=zip(grads,[W,b]))
        if step % 100 == 0:
            print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
print("W = {}, B = {}".format(W.numpy(), b.numpy()))
 
Iter: 0, Loss: 0.6931
Iter: 100, Loss: 0.6931
Iter: 200, Loss: 0.6931
Iter: 300, Loss: 0.6931
Iter: 400, Loss: 0.6931
Iter: 500, Loss: 0.6931
Iter: 600, Loss: 0.6931
Iter: 700, Loss: 0.6931
Iter: 800, Loss: 0.6931
Iter: 900, Loss: 0.6931
Iter: 1000, Loss: 0.6931
W = [[0.]
 [0.]], B = [0.]
 

이 포스팅은 부스트코스 강의, 모두를위한 딥러닝 강의를 참고하였습니다.

In [ ]:
 

'Tensorflow > DNN' 카테고리의 다른 글

DNN_XOR구현  (0) 2020.08.12
NN_XOR 구현  (0) 2020.08.08

Tensorflow 다중선형회귀 공부

Tensorflow/ML

 

 

 

다중 선형회귀 복습

지난번포스팅했던 다중 선형회귀를 복습하는 시간을 가지겠습니다.
자세한 포스팅은 이전에 했기때문에 주석을 최소화 하였습니다.

In [280]:
import tensorflow as tf
import numpy as np
print(tf.__version__)
 
2.1.0
 

변수 만들기(컴프리헨션 복습)

In [281]:
test1 = [i for i in range(0,10) if i>2]
test1
Out[281]:
[3, 4, 5, 6, 7, 8, 9]
In [282]:
test1 = list(range(0,10))
test2 = list(range(10,20))
print(test1)
print(test2)
 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [283]:
test3 = []
for i,v in zip(test1,test2):
    test3.append([i,v])
test3
Out[283]:
[[0, 10],
 [1, 11],
 [2, 12],
 [3, 13],
 [4, 14],
 [5, 15],
 [6, 16],
 [7, 17],
 [8, 18],
 [9, 19]]
 

x,y, 값 나눠주기

In [284]:
x1 = [x[0] for x in test3]
x2 = [x[1] for x in test3]
y = [i for i in range(100,110)]
In [285]:
print(x1)
print(x2)
print(y)
 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
In [288]:
#x변수가 2개이기 때문에 W도 2개 설정
tf.random.set_seed(0)
W1 = tf.Variable(tf.random.uniform((1,),1., 10.0 ))
W2 = tf.Variable(tf.random.uniform((1,),1., 10.0 ))
b = tf.Variable(tf.random.uniform((1,),1., 10.0 ))
In [287]:
learning_rate = tf.Variable(0.001)
for i in range(1001):
    with tf.GradientTape() as tape:
        hypothesis = W1 * x1 + W2* x2 + b
        cost = tf.reduce_mean(tf.square(hypothesis - y))
    W1_grad, W2_grad, b_grad = tape.gradient(cost, [W1,W2,b])
    W1.assign_sub(learning_rate * W1_grad)
    W2.assign_sub(learning_rate * W2_grad)
    b.assign_sub(learning_rate * b_grad)
    
    if i % 50 ==0:
        print("{:5} | {:10.6f} | {:10.4f} | {:10.4f} | {:10.6f}".format(
        i, cost.numpy(), W1.numpy()[0], W2.numpy()[0], b.numpy()[0]))
 
    0 | 616.380981 |     3.4714 |     5.8110 |   2.753797
   50 | 282.371643 |    -0.0978 |     6.7484 |   3.204454
  100 | 141.552185 |    -2.5705 |     7.5713 |   3.534010
  150 |  70.959732 |    -4.3213 |     8.1539 |   3.767345
  200 |  35.571896 |    -5.5608 |     8.5664 |   3.932551
  250 |  17.832087 |    -6.4385 |     8.8585 |   4.049521
  300 |   8.939185 |    -7.0599 |     9.0652 |   4.132339
  350 |   4.481170 |    -7.4998 |     9.2117 |   4.190976
  400 |   2.246401 |    -7.8113 |     9.3153 |   4.232491
  450 |   1.126115 |    -8.0319 |     9.3887 |   4.261886
  500 |   0.564514 |    -8.1880 |     9.4407 |   4.282698
  550 |   0.282984 |    -8.2986 |     9.4775 |   4.297431
  600 |   0.141857 |    -8.3769 |     9.5035 |   4.307865
  650 |   0.071112 |    -8.4323 |     9.5220 |   4.315252
  700 |   0.035649 |    -8.4715 |     9.5350 |   4.320483
  750 |   0.017869 |    -8.4993 |     9.5443 |   4.324186
  800 |   0.008958 |    -8.5190 |     9.5508 |   4.326808
  850 |   0.004490 |    -8.5329 |     9.5554 |   4.328665
  900 |   0.002251 |    -8.5428 |     9.5587 |   4.329979
  950 |   0.001129 |    -8.5498 |     9.5610 |   4.330909
 1000 |   0.000566 |    -8.5547 |     9.5627 |   4.331569
 

변수 3개 메트릭스 활용

변수만들기

In [289]:
x1 = [x for x in range(0,10)]
x2 = [x for x in range(10,20)]
x3 = [x for x in range(30,40)]
y = [x for x in range(100,110)]
In [290]:
print(x1)
print(x2)
print(x3)
print(y)
 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
In [291]:
#변수를 한 메트릭스로 만들기
data =np.array([[i,v,z,h] for i,v,z,h in zip(x1,x2,x3,y)],dtype =np.float32)
data
Out[291]:
array([[  0.,  10.,  30., 100.],
       [  1.,  11.,  31., 101.],
       [  2.,  12.,  32., 102.],
       [  3.,  13.,  33., 103.],
       [  4.,  14.,  34., 104.],
       [  5.,  15.,  35., 105.],
       [  6.,  16.,  36., 106.],
       [  7.,  17.,  37., 107.],
       [  8.,  18.,  38., 108.],
       [  9.,  19.,  39., 109.]], dtype=float32)
In [321]:
#X, Y 로 데이터 나눠주기
X = data[:,:-1]
Y = data[:,[-1]]
print(X)
print(Y)
 
[[ 0. 10. 30.]
 [ 1. 11. 31.]
 [ 2. 12. 32.]
 [ 3. 13. 33.]
 [ 4. 14. 34.]
 [ 5. 15. 35.]
 [ 6. 16. 36.]
 [ 7. 17. 37.]
 [ 8. 18. 38.]
 [ 9. 19. 39.]]
[[100.]
 [101.]
 [102.]
 [103.]
 [104.]
 [105.]
 [106.]
 [107.]
 [108.]
 [109.]]
In [322]:
print(X.shape)
print(X.shape[1])
 
(10, 3)
3
In [323]:
#W, b 설정해주기
W = tf.Variable(tf.random.normal((X.shape[1],1)))
b = tf.Variable(tf.random.normal((1,)))
In [324]:
# 예측 모델 및 경사하강법 적용
def predict(X):
    return tf.matmul(X,W) + b

learning_rate = 0.00001


for i in range(1001):
    with tf.GradientTape() as tape:
        cost =tf.reduce_mean((tf.square(predict(X) - y)))
        
    W_grad, b_grad = tape.gradient(cost, [W,b])
    
    W.assign_sub(learning_rate * W_grad)
    b.assign_sub(learning_rate * b_grad)
    
    if i % 500 ==0:
        print("{:5} | {:10.6f} | {:10.4f} | {:10.4f} | {:10.6f}".format(
            i, cost.numpy(), W.numpy()[0][0], W.numpy()[1][0], b.numpy()[0]))
 
    0 | 3581.468018 |     1.3541 |     0.4929 |  -2.126617
  500 | 186.300980 |     1.2123 |     0.8905 |  -2.072671
 1000 | 159.831528 |     0.9086 |     0.7253 |  -2.058817
In [325]:
#W값 확인
print(W)
 
<tf.Variable 'Variable:0' shape=(3, 1) dtype=float32, numpy=
array([[0.9085694 ],
       [0.72533375],
       [2.6267443 ]], dtype=float32)>
In [307]:
#X값으로 해 도출
predict(X)
Out[307]:
<tf.Tensor: shape=(10, 1), dtype=float32, numpy=
array([[ 89.7837  ],
       [ 92.84181 ],
       [ 95.899925],
       [ 98.958046],
       [102.01615 ],
       [105.07428 ],
       [108.13239 ],
       [111.190506],
       [114.24863 ],
       [117.30674 ]], dtype=float32)>
In [308]:
#임의의 값으로 해 도출
predict([[ 1.,  1.,  4.],[ 145.,  50.,  50.]]).numpy()
Out[308]:
array([[11.6773615],
       [87.66279  ]], dtype=float32)

'Tensorflow > ML' 카테고리의 다른 글

Python Logistic Regression  (0) 2020.07.28
Python Tensorflow 다중선형회귀  (0) 2020.07.25
Python Tensorflow 단순선형회귀  (0) 2020.07.20

Python Logistic Regression

Tensorflow/ML

 

 

 

Logistic_Regression(Classification)

로지스틱 회귀(분류)

안녕하세요. 이번 포스팅은 로지스틱 회귀에대해 포스팅을 진행하겠습니다.
로지스틱 회귀란 = 독립 변수의 선형 결합을 이용하여 사건의 발생 가능성을 예측하는 통계기법(출처 나무위키)

흔히 로지스틱 회귀는 종속변수가 2개(이항, boolean, True or False)인경우를 말하며, 이를 Classification 분류 기법이라고 한다.

종속변수가 2개이상일 경우 다항로지스틱 회귀라고 한다.(Multinormial logisitic regression).

이번 포스팅은 Classification에 관한 포스팅입니다.

필요한 모듈 세팅 및 tensorflow버전 확인

In [1]:
import numpy as pn
import matplotlib.pyplot as plt
import tensorflow as tf

tf.random.set_seed(0)
print(tf.__version__)
 
2.1.0
 

데이터 세팅

In [2]:
#x1, x2를 각각 x_train의 2차원배열로 정의해줍니다.
x_train = [[1., 6.],
          [2., 5.],
          [3., 4.],
          [4., 3.],
          [5., 2.],
          [6., 1.]]

#각 배열의 도출 값을 선언합니다.
#1,6 -> 0
#6,1 -> 1

y_train = [[0.],
          [0.],
          [0.],
          [1.],
          [1.],
          [1.]]
In [5]:
#데이터 확인
print(x_train, y_train)
 
[[1.0, 6.0], [2.0, 5.0], [3.0, 4.0], [4.0, 3.0], [5.0, 2.0], [6.0, 1.0]] [[0.0], [0.0], [0.0], [1.0], [1.0], [1.0]]
 

테스트 할 데이터 세팅

In [36]:
#test할 데이터를 세팅해 줍니다.
#2,6이 1인지 확인하기 위합니다.
x_test = [[2.,6.]]
y_test = [[0.]]
In [37]:
x_test,y_test
Out[37]:
([[2.0, 6.0]], [[0.0]])
 

x값 할당해 주기

x_train에 있던 값들을 각각 x1, x2로 할당해 주겠습니다. 이때, 리스트 형식으로 할당해 주는데요,
복습차원에서 리스트 컴프리헨션과, append방법 두가지를 활용해 보겠습니다.

In [38]:
x1 = [x[0] for x in x_train]
x1
Out[38]:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
In [39]:
x1=[]
for x in range(len(x_train)):
    x1.append(x_train[x][0])
x1
Out[39]:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
In [40]:
x2 = [x[1] for x in x_train]
x2
Out[40]:
[6.0, 5.0, 4.0, 3.0, 2.0, 1.0]
In [41]:
x2=[]
for x in range(len(x_train)):
    x2.append(x_train[x][1])
x2
Out[41]:
[6.0, 5.0, 4.0, 3.0, 2.0, 1.0]
 

데이터 그래프로 확인하기

현재까지 할당된, 데이터를 그래프에서 확인해 보겠습니다.
데이터각각에 색을 입혀줄껀데요, 이것도 역시 리스트컴프리헨션을 복습하겠습니다.

In [42]:
colors = []
for y in range(len(y_train)):
    colors.append(int(y_train[y][0]))
colors
Out[42]:
[0, 0, 0, 1, 1, 1]
In [43]:
colors = [int(y[0]) for y in y_train]
colors
Out[43]:
[0, 0, 0, 1, 1, 1]
In [44]:
#0은 보라색, 1은 노란색으로 표시가 됩니다.
colors = [int(y[0]) for y in y_train]

#x1, x2에 해당되는 값들은 삼각형으로 표시
plt.scatter(x1,x2, c= colors, marker='^')

#제가 찾고자 했던 x_test값 (2,6)은 빨간색으로 표시했습니다.
plt.scatter(x_test[0][0], x_test[0][1], c='red')

plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
 
 

Logistic Classification모델 만들기

In [93]:
#dataset 만들기
#학습시킬 값을 dataset에 담아준다.
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset
Out[93]:
<TensorSliceDataset shapes: ((2,), (1,)), types: (tf.float32, tf.float32)>
 

dataset 살펴보기

현재 dataset은 6슬라이스로 이루어져 있다.
1슬라이스 => [1,6],[0]
2슬라이스 => [2,5],[0] ....

In [95]:
#리스트 컴프리헨션
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 6.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 5.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([3., 4.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([4., 3.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([5., 2.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 1.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>)]
6
In [96]:
#append로 확인하기
elem2= []
for i in dataset:
    elem2.append(i)
print(elem2)
len(elem2)
 
[(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 6.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 5.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([3., 4.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([4., 3.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([5., 2.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>), (<tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 1.], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>)]
Out[96]:
6
 

W, b 할당해 주기

W,b초기값을 할당해 줍니다. x가 x1,x2 2개의 변수였기 때문에 W는 2행1열의 배열을 선언해준다.
b는 1행 1열로 선언해 준다.

In [105]:
#초기값을 tf.random.normal로 설정해주기
W = tf.Variable(tf.random.normal((2, 1)))
b = tf.Variable(tf.random.normal((1,)))
print(W.numpy(),b.numpy())
 
[[-2.1278012 ]
 [ 0.42648628]] [-1.4933363]
In [111]:
#초기값을 tf.zeros로 설정해 주기
W = tf.Variable(tf.zeros([2,1]), name= 'weight')
b = tf.Variable(tf.zeros([1]), name='bias')
print(W.numpy(),b.numpy())
 
[[0.]
 [0.]] [0.]
 

시그모이드 함수 구현

In [106]:
def logistic_regression(features):
    hypothesis = tf.divide(1., 1. + tf.exp(tf.matmul(features, W) + b))
    return hypothesis
    
 

cost 함수 구현, 러닝레이트 선언

In [107]:
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(logistic_regression(features)) + (1-labels) * tf.math.log(1-hypothesis))
    return cost
optimizer = tf.keras.optimizers.SGD(learning_rate =0.01)
 

결과값 도출 함수 구현

시그모이드 함수로 도출된 hypothesis를 0 or 1로 cast해준다.

tf.cast => 조건이 참일경우 1, 거짓일 경우 0출력
tf.equal => 주어인 값이 같은경우 True, 다를경우 False
아래는 cast와 equal를 이해하기 쉽도록 예시를 작성 하였습니다.

In [119]:
test1 = 0.3
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[119]:
0.0
In [129]:
test1 = 0.6
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[129]:
1.0
In [130]:
test1 = 0.6
test2 = 0.6
test3 = tf.equal(test1,test2)
test3.numpy()
Out[130]:
True
In [131]:
test4 = 0.5
test5 = 0.6
test6 = tf.equal(test4,test5)
test6.numpy()
Out[131]:
False
In [136]:
test7 = tf.cast(tf.equal(test1,test2),dtype = tf.float32)
test7.numpy()
Out[136]:
1.0
In [137]:
test8 = tf.cast(tf.equal(test4,test5),dtype = tf.float32)
test8.numpy()
Out[137]:
0.0
In [141]:
def accuracy_fn(hypothesis, labels):
    predicted = tf.cast(hypothesis > 0.5, dtype =tf.float32)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels),dtype =tf.int32))
    return accuracy
 

경사하강법(미분)

In [142]:
def grad(features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(logistic_regression(features),features,labels)
        return tape.gradient(loss_value, [W,b])
    
 

반복 및 결과 값 도출

어큐러시가 1이 나왔음으로,
위에서 제시했던 test값은 참임

In [144]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(len(x_train))):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test),y_test)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0908
Iter : 100, Loss: 0.0863
Iter : 200, Loss: 0.0823
Iter : 300, Loss: 0.0787
Iter : 400, Loss: 0.0755
Iter : 500, Loss: 0.0726
Iter : 600, Loss: 0.0699
Iter : 700, Loss: 0.0675
Iter : 800, Loss: 0.0652
Iter : 900, Loss: 0.0631
Iter : 1000, Loss: 0.0612
Testset Accuracy: 1.000000
 

test값 변환 후 결과 값 도출

어큐러시가 0이 나왔음으로 새롭게 제시한 test값은 거짓임

In [147]:
x_test2 = [[2.,6.]]
y_test2 = [[1.]]
In [148]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(len(x_train))):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test2),y_test2)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0470
Iter : 100, Loss: 0.0460
Iter : 200, Loss: 0.0450
Iter : 300, Loss: 0.0440
Iter : 400, Loss: 0.0431
Iter : 500, Loss: 0.0422
Iter : 600, Loss: 0.0414
Iter : 700, Loss: 0.0406
Iter : 800, Loss: 0.0398
Iter : 900, Loss: 0.0391
Iter : 1000, Loss: 0.0384
Testset Accuracy: 0.000000
 

batch값 설정

batch값을 2로 설정 하였는데,
아래 예 처럼 6개의 슬라이스를 3번에 나눠 각각 학습이 된다.

In [151]:
#반복 횟수 선언
EPOCHS = 1001

for step in range(EPOCHS):
    #dataset을 몇 묶음씩 학습 시킬 것인지 정해준다
    #batch size를 선언해줄 수 있다.
    for features, labels in iter(dataset.batch(2)):
        #print(features)
        #print(labels)
        hypothesis = logistic_regression(features)
        grads = grad(features, labels)
        optimizer.apply_gradients(grads_and_vars =zip(grads,[W,b]))
        if step % 100 ==0:
            print("Iter : {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
test_acc = accuracy_fn(logistic_regression(x_test2),y_test2)
print("Testset Accuracy: {:4f}".format(test_acc))
 
Iter : 0, Loss: 0.0009
Iter : 0, Loss: 0.1133
Iter : 0, Loss: 0.0009
Iter : 100, Loss: 0.0007
Iter : 100, Loss: 0.1076
Iter : 100, Loss: 0.0007
Iter : 200, Loss: 0.0006
Iter : 200, Loss: 0.1024
Iter : 200, Loss: 0.0006
Iter : 300, Loss: 0.0005
Iter : 300, Loss: 0.0977
Iter : 300, Loss: 0.0005
Iter : 400, Loss: 0.0005
Iter : 400, Loss: 0.0934
Iter : 400, Loss: 0.0005
Iter : 500, Loss: 0.0004
Iter : 500, Loss: 0.0895
Iter : 500, Loss: 0.0004
Iter : 600, Loss: 0.0004
Iter : 600, Loss: 0.0858
Iter : 600, Loss: 0.0004
Iter : 700, Loss: 0.0003
Iter : 700, Loss: 0.0825
Iter : 700, Loss: 0.0003
Iter : 800, Loss: 0.0003
Iter : 800, Loss: 0.0794
Iter : 800, Loss: 0.0003
Iter : 900, Loss: 0.0003
Iter : 900, Loss: 0.0765
Iter : 900, Loss: 0.0003
Iter : 1000, Loss: 0.0002
Iter : 1000, Loss: 0.0739
Iter : 1000, Loss: 0.0002
Testset Accuracy: 0.000000
 

해당 포스팅은 부스트코스 강의와, 텐서플로우공식 홈페이지를 참고하여 작성하였습니다.

'Tensorflow > ML' 카테고리의 다른 글

Tensorflow 다중선형회귀 공부  (0) 2020.08.07
Python Tensorflow 다중선형회귀  (0) 2020.07.25
Python Tensorflow 단순선형회귀  (0) 2020.07.20