Created
November 28, 2016 12:46
-
-
Save dj-shin/d623099e67075070a57266a8a5e91ef1 to your computer and use it in GitHub Desktop.
Project illegal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
import numpy as np | |
import math | |
from scipy import misc | |
import glob | |
from ops import * | |
def label(path): | |
result = [0 for _ in range(100)] | |
index = 0 | |
result[int(path.split('/')[-1][:2])] = 1 | |
return np.array(result) | |
png = [(misc.imread(image_path), label(image_path)) for image_path in glob.glob('./captcha/*.png')] | |
index = 0 | |
def next_batch(batch_size): | |
global index | |
xs, ys = [], [] | |
for i in range(batch_size): | |
xs.append(png[index % len(png)][0]) | |
ys.append(png[index % len(png)][1]) | |
index += 1 | |
index %= len(png) | |
return xs, ys | |
batch_size = 32 | |
x = tf.placeholder(tf.float32, [batch_size, 26, 52, 3]) # input | |
y_ = tf.placeholder(tf.float32, [batch_size, 100]) # target | |
h1 = tf.nn.relu(conv2d(x, 48, name='conv1')) # stride is 2 (default) | |
h2 = tf.nn.relu(conv2d(h1, 64, name='conv2')) | |
h3 = tf.nn.relu(conv2d(h2, 128, name='conv3')) | |
h4 = tf.reshape(h3, [batch_size, 7 * 4 * 128]) | |
h4 = linear(h4, 100) | |
h4 = tf.nn.relu(h4) | |
y = tf.reshape(tf.nn.softmax(h4), [batch_size, 100]) | |
# loss | |
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) | |
train_step = tf.train.AdamOptimizer(0.01, beta1=0.5).minimize(cross_entropy) | |
# train | |
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9) # remove gpu_options if you are using cpu. | |
def test_data(batch_size): | |
with open('./test_data/label.txt', 'rt') as f: | |
xs, ys = [], [] | |
for i in range(batch_size): | |
x = misc.imread('./test_data/' + str(i) + '.png') | |
ans = int(f.readline()) | |
y = [0 for _ in range(100)] | |
y[ans] = 1 | |
xs.append(x) | |
ys.append(y) | |
return xs, ys | |
test_images, test_labels = test_data(batch_size) | |
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess: | |
tf.initialize_all_variables().run() | |
for i in range(3000): | |
# From input | |
batch_xs, batch_ys = next_batch(batch_size) | |
train_step.run({x: batch_xs, y_:batch_ys}) | |
if i % 2 == 0: | |
print(cross_entropy.eval({x: test_images, y_: test_labels})) | |
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) | |
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) | |
print(accuracy.eval({x: test_images, y_: test_labels})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment