3.1 단층 신경망 구조
데이터: 바이러스 감염(특징2)
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import multivariate_normal, permutation
import pandas as pd
from pandas import DataFrame, Series
%matplotlib inline
np.random.seed(20160614)
tf.set_random_seed(20160614)
# 트레이닝 세트 데이터를 생성한다.
def generate_datablock(n, mu, var, t):
data = multivariate_normal(mu, np.eye(2)*var, n)
df = DataFrame(data, columns=['x1','x2'])
df['t'] = t
return df
df0 = generate_datablock(15, [7,7], 22, 0) # 개수, 평균, 분산?, 레이블
df1 = generate_datablock(15, [22,7], 22, 0)
df2 = generate_datablock(10, [7,22], 22, 0)
df3 = generate_datablock(25, [20,20], 22, 1)
df = pd.concat([df0, df1, df2, df3], ignore_index=True)
train_set = df.reindex(permutation(df.index)).reset_index(drop=True)
# (x1, x2)와 t를 각각 모은 것을 NumPy의 array 오브젝트로 추출해둔다.
train_x = train_set[['x1','x2']].as_matrix()
train_t = train_set['t'].as_matrix().reshape([len(train_set), 1])
# 단층 신경망을 이용한 이항 분류기 모델을 정의한다.
num_units = 2
mult = train_x.flatten().mean()
x = tf.placeholder(tf.float32, [None, 2])
w1 = tf.Variable(tf.truncated_normal([2, num_units]))
b1 = tf.Variable(tf.zeros([num_units]))
hidden1 = tf.nn.tanh(tf.matmul(x, w1) + b1*mult)
w0 = tf.Variable(tf.zeros([num_units, 1]))
b0 = tf.Variable(tf.zeros([1]))
p = tf.nn.sigmoid(tf.matmul(hidden1, w0) + b0*mult)
# 오차함수, 트레이닝 알고리즘, 정답률 계산식
t = tf.placeholder(tf.float32, [None, 1])
loss = -tf.reduce_sum(t*tf.log(p) + (1-t)*tf.log(1-p))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
correct_prediction = tf.equal(tf.sign(p-0.5), tf.sign(t-0.5))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
# 파라미터 최적화를 1000회 반복한다.
i = 0
for _ in range(1000):
i += 1
sess.run(train_step, feed_dict={x:train_x, t:train_t})
if i % 100 == 0:
loss_val, acc_val = sess.run(
[loss, accuracy], feed_dict={x:train_x, t:train_t})
print ('Step: %d, Loss: %f, Accuracy: %f'
% (i, loss_val, acc_val))
train_set1 = train_set[train_set['t']==1]
train_set2 = train_set[train_set['t']==0]
# 그래프
fig = plt.figure(figsize=(6,6))
subplot = fig.add_subplot(1,1,1)
subplot.set_ylim([0,30])
subplot.set_xlim([0,30])
subplot.scatter(train_set1.x1, train_set1.x2, marker='x')
subplot.scatter(train_set2.x1, train_set2.x2, marker='o')
locations = []
for x2 in np.linspace(0,30,100):
for x1 in np.linspace(0,30,100):
locations.append((x1,x2))
p_vals = sess.run(p, feed_dict={x:locations})
p_vals = p_vals.reshape((100,100))
subplot.imshow(p_vals, origin='lower', extent=(0,30,0,30),
cmap=plt.cm.gray_r, alpha=0.5)
* 은닉계층 개수 늘리기
num_units = 4
train_step = tf.train.GradientDescentOptimized(0.0005).minimize(loss)
for _ in range(4000):
* 활성화 함수 : 하이퍼볼릭 탄젠트 -> 렐루 로 변경
hidden1 = tf.nn.relu(tf.matmul(x, w1) + b1*mult)
3.2 단층 신경망 - 필기 문자 분류
데이터: 필기문자 MNIST(특징 784개)
3.3 다층 신경망
3.1 단층 신경망 구조
3.2 단층 신경망 - 필기 문자 분류
3.3 다층 신경망
...
http://playground.tensorflow.org
'python 및 머신러닝 > 텐서플로로 시작하는 딥러닝' 카테고리의 다른 글
| 텐서플로로 시작하는 딥러닝 4장 - 은닉층의 역할 (0) | 2017.10.10 |
|---|---|
| 텐서플로로 시작하는 딥러닝 4장 - 합성곱 필터 (0) | 2017.09.26 |
| 텐서플로로 시작하는 딥러닝 1장 (0) | 2017.09.25 |