如何使用深度学习破解验证码 keras 连续验证码

# -*- coding: utf-8 -*-
NUMBER = ''
CHAR_SMALL = 'abcdefghijklmnopqrstuvwxyz'
CHAR_BIG = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
MAX_CAPTCHA = 6
# 测试1位的训练准确率
VALIDATE_STRING = NUMBER + CHAR_SMALL
# + CHAR_BIG
CHAR_SET_LEN = len(VALIDATE_STRING)
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
FONT_SIZE = 35
MAX_ACCURACY = 0.9
123456789101112131415
# -*- coding: utf-8 -*-NUMBER = ''CHAR_SMALL = 'abcdefghijklmnopqrstuvwxyz'CHAR_BIG = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'&MAX_CAPTCHA = 6&&# 测试1位的训练准确率VALIDATE_STRING = NUMBER + CHAR_SMALL&&# + CHAR_BIGCHAR_SET_LEN = len(VALIDATE_STRING)&IMAGE_HEIGHT = 60IMAGE_WIDTH = 160FONT_SIZE = 35&MAX_ACCURACY = 0.9&
生成数据集
# -*- coding: utf-8 -*-
from captcha.image import ImageCaptcha
import numpy as np
import matplotlib.pyplot as plt
# from config import NUMBER, CHAR_SMALL, CHAR_BIG, MAX_CAPTCHA, CHAR_SET_LEN, FONT_SIZE
import config
from PIL import Image
import random
char_dict = {}
number_dict = {}
# 生成随机的指定的字符串
def __gen_random_captcha_text(char_set=config.VALIDATE_STRING, size=None):
# char_set must be a str
if not char_set or not isinstance(char_set, str):
raise ValueError('get the empty char_set')
result = list(char_set)
random.shuffle(result)
# 返回字符串
return ''.join(result[0:size])
def gen_random_captcha_image():
image = ImageCaptcha(width=config.IMAGE_WIDTH, height=config.IMAGE_HEIGHT,font_sizes=[config.FONT_SIZE])
text = __gen_random_captcha_text(size=config.MAX_CAPTCHA)
captcha = image.generate(text)
captcha_image = Image.open(captcha)
captcha_source = np.array(captcha_image)
return text, captcha_source
# always gen the require image height ,and width image
def gen_require_captcha_image():
text, image = gen_random_captcha_image()
if image.shape == (config.IMAGE_HEIGHT, config.IMAGE_WIDTH, 3):
return text, image
# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用,对于抽取特征也没啥用)
def convert2gray(img):
if len(img.shape) & 2:
gray = np.mean(img, -1)
# 上面的转法较快,正规转法如下
# r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
# gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
return img
# prepare the char to index
def prepare_char_dict():
if char_dict:
return char_dict
for index, val in enumerate(config.VALIDATE_STRING):
char_dict[val] = index
return char_dict
def prepare_number_dict():
if number_dict:
return number_dict
for index, val in enumerate(config.VALIDATE_STRING):
number_dict[index] = val
return number_dict
def text_to_array(text):
char_dict_tmp = prepare_char_dict()
arr = np.zeros(config.MAX_CAPTCHA * config.CHAR_SET_LEN, dtype=np.int8)
for i, p in enumerate(text):
key_index = char_dict_tmp[p]
index = i * config.CHAR_SET_LEN + key_index
arr[index] = 1
return arr
def array_to_text(arr):
num_dict_tmp = prepare_number_dict()
char_pos = arr.nonzero()[0]
for index, val in enumerate(char_pos):
if index == 0:
key_index = val % (index * config.CHAR_SET_LEN)
text.append(num_dict_tmp[key_index])
return ''.join(text)
def show_image_text():
text, image = gen_random_captcha_image()
f = plt.figure()
ax = f.add_subplot(111)
ax.text(0.1, 0.9, text, ha='center', va='center', transform=ax.transAxes)
plt.imshow(image)
plt.show()
if __name__ == '__main__':
# __do_image_text()
# arr = text_to_array('0142')
# print '==========='
# print array_to_text(arr)
show_image_text()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
# -*- coding: utf-8 -*-&from captcha.image import ImageCaptchaimport numpy as npimport matplotlib.pyplot as plt# from config import NUMBER, CHAR_SMALL, CHAR_BIG, MAX_CAPTCHA, CHAR_SET_LEN, FONT_SIZEimport configfrom PIL import Imageimport random&char_dict = {}number_dict = {}&&# 生成随机的指定的字符串def __gen_random_captcha_text(char_set=config.VALIDATE_STRING, size=None):&&&&# char_set must be a str&&&&if not char_set or not isinstance(char_set, str):&&&&&&&&raise ValueError('get the empty char_set')&&&&&# 随机&&&&result = list(char_set)&&&&random.shuffle(result)&&&&&# 返回字符串&&&&return ''.join(result[0:size])&&def gen_random_captcha_image():&&&&image = ImageCaptcha(width=config.IMAGE_WIDTH, height=config.IMAGE_HEIGHT,font_sizes=[config.FONT_SIZE])&&&&&text = __gen_random_captcha_text(size=config.MAX_CAPTCHA)&&&&captcha = image.generate(text)&&&&captcha_image = Image.open(captcha)&&&&captcha_source = np.array(captcha_image)&&&&return text, captcha_source&&# always gen the require image height ,and width imagedef gen_require_captcha_image():&&&&while 1:&&&&&&&&text, image = gen_random_captcha_image()&&&&&&&&if image.shape == (config.IMAGE_HEIGHT, config.IMAGE_WIDTH, 3):&&&&&&&&&&&&return text, image&&# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用,对于抽取特征也没啥用)def convert2gray(img):&&&&if len(img.shape) & 2:&&&&&&&&gray = np.mean(img, -1)&&&&&&&&# 上面的转法较快,正规转法如下&&&&&&&&# r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]&&&&&&&&# gray = 0.2989 * r + 0.5870 * g + 0.1140 * b&&&&&&&&return gray&&&&else:&&&&&&&&return img&&# prepare the char to indexdef prepare_char_dict():&&&&if char_dict:&&&&&&&&return char_dict&&&&&for index, val in enumerate(config.VALIDATE_STRING):&&&&&&&&char_dict[val] = index&&&&&return char_dict&&def prepare_number_dict():&&&&if number_dict:&&&&&&&&return number_dict&&&&&for index, val in enumerate(config.VALIDATE_STRING):&&&&&&&&number_dict[index] = val&&&&&return number_dict&&def text_to_array(text):&&&&char_dict_tmp = prepare_char_dict()&&&&&arr = np.zeros(config.MAX_CAPTCHA * config.CHAR_SET_LEN, dtype=np.int8)&&&&for i, p in enumerate(text):&&&&&&&&key_index = char_dict_tmp[p]&&&&&&&&index = i * config.CHAR_SET_LEN + key_index&&&&&&&&arr[index] = 1&&&&&return arr&&def array_to_text(arr):&&&&num_dict_tmp = prepare_number_dict()&&&&text = []&&&&char_pos = arr.nonzero()[0]&&&&for index, val in enumerate(char_pos):&&&&&&&&if index == 0:&&&&&&&&&&&&index = 1&&&&&&&&key_index = val % (index * config.CHAR_SET_LEN)&&&&&&&&text.append(num_dict_tmp[key_index])&&&&return ''.join(text)&def show_image_text():&&&&text, image = gen_random_captcha_image()&&&&&f = plt.figure()&&&&ax = f.add_subplot(111)&&&&ax.text(0.1, 0.9, text, ha='center', va='center', transform=ax.transAxes)&&&&plt.imshow(image)&&&&&plt.show()&#if __name__ == '__main__':&&&&# __do_image_text()&&&&# arr = text_to_array('0142')&&&&# print '==========='&&&&# print array_to_text(arr)&&&&show_image_text()&&
正式训练数模型
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
from gen_image import text_to_array
from config import MAX_CAPTCHA, CHAR_SET_LEN, IMAGE_HEIGHT, IMAGE_WIDTH, MAX_ACCURACY
from gen_image import gen_require_captcha_image
x_input = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])
y_input = tf.placeholder(tf.float32, [None, CHAR_SET_LEN * MAX_CAPTCHA])
keep_prob = tf.placeholder(tf.float32)
# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用,对于抽取特征也没啥用)
def convert2gray(img):
if len(img.shape) & 2:
gray = np.mean(img, -1)
return gray
return img
def __weight_variable(shape, stddev=0.01):
initial = tf.random_normal(shape, stddev=stddev)
return tf.Variable(initial)
def __bias_variable(shape, stddev=0.1):
initial = tf.random_normal(shape=shape, stddev=stddev)
return tf.Variable(initial)
def __conv2d(x, w):
# strides 代表移动的平长
return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
def __max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 100个一个批次
def gen_next_batch(batch_size=100):
batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])
batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])
for i in xrange(batch_size):
text, image = gen_require_captcha_image()
# 转成灰度图片,因为颜色对于提取字符形状是没有意义的
image = convert2gray(image)
batch_x[i, :] = image.flatten() / 255
batch_y[i, :] = text_to_array(text)
return batch_x, batch_y
def create_layer(x_input, keep_prob):
x_image = tf.reshape(x_input, shape=[-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1])
# 定义第1个卷积层
w_c1 = __weight_variable([5, 5, 1, 32], stddev=0.1)
# 3x3 第一层32个卷积核 采用黑白色
b_c1 = __bias_variable([32], stddev=0.1)
h_c1 = tf.nn.relu(tf.nn.bias_add(__conv2d(x_image, w_c1), b_c1))
# 定义第一个卷积层
h_pool1 = __max_pool_2x2(h_c1)
# 定义第一个池化层
# h_pool1 = tf.nn.dropout(h_pool1, keep_prob)
# 定义第2个卷积层
w_c2 = __weight_variable([5, 5, 32, 64], stddev=0.1)
b_c2 = __bias_variable([64], stddev=0.1)
h_c2 = tf.nn.relu(tf.nn.bias_add(__conv2d(h_pool1, w_c2), b_c2))
h_pool2 = __max_pool_2x2(h_c2)
# h_pool2 = tf.nn.dropout(h_pool2, keep_prob)
# 定义第3个卷积层
w_c3 = __weight_variable([5, 5, 64, 64], stddev=0.1)
b_c3 = __bias_variable([64], stddev=0.1)
h_c3 = tf.nn.relu(tf.nn.bias_add(__conv2d(h_pool2, w_c3), b_c3))
h_pool3 = __max_pool_2x2(h_c3)
# h_pool3 = tf.nn.dropout(h_pool3, keep_prob)
# 3层池化之后 width 144 / 8 = 18
# height 64 / 8 = 8
# 全链接层1
w_fc1 = __weight_variable([20 * 8 * 64, 1024], stddev=0.1)
b_fc1 = __bias_variable([1024])
h_pool3_flat = tf.reshape(h_pool3, [-1, w_fc1.get_shape().as_list()[0]])
h_fc1 = tf.nn.relu(tf.add(tf.matmul(h_pool3_flat, w_fc1), b_fc1))
# drop out 内容0
h_fc1_dropout = tf.nn.dropout(h_fc1, keep_prob)
# 全链接层2
w_output = __weight_variable([1024, MAX_CAPTCHA * CHAR_SET_LEN], stddev=0.1)
b_output = __bias_variable([MAX_CAPTCHA * CHAR_SET_LEN])
y_output = tf.add(tf.matmul(h_fc1_dropout, w_output), b_output)
return y_output
def create_loss(layer, y_input):
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_input, logits=layer))
return loss
def create_accuracy(output, y_input):
predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
max_idx_p = tf.argmax(predict, 2)
max_idx_l = tf.argmax(tf.reshape(y_input, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
correct_pred = tf.equal(max_idx_p, max_idx_l)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
return accuracy
def train():
# create the layer and loss
layer_output = create_layer(x_input, keep_prob)
loss = create_loss(layer_output, y_input)
accuracy = create_accuracy(layer_output, y_input)
train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
# save model
saver = tf.train.Saver()
with tf.Session() as sess:
tf.global_variables_initializer().run()
while acc & MAX_ACCURACY:
batch_x, batch_y = gen_next_batch(64)
_, _loss = sess.run([train_step, loss],
feed_dict={x_input: batch_x, y_input: batch_y, keep_prob: 0.75})
print(i, _loss)
# 每100 step计算一次准确率
if i % 50 == 0:
batch_x_test, batch_y_test = gen_next_batch(100)
acc = sess.run(accuracy, feed_dict={x_input: batch_x_test, y_input: batch_y_test, keep_prob: 1.})
print('step is %s' % i, 'and accy is %s' % acc)
# 如果准确率大于50%,保存模型,完成训练
if acc & MAX_ACCURACY:
print('current acc & %s
,stop now' % MAX_ACCURACY)
saver.save(sess, "break.model", global_step=i)
if __name__ == '__main__':
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
# -*- coding: utf-8 -*-import tensorflow as tfimport numpy as npfrom gen_image import text_to_arrayfrom config import MAX_CAPTCHA, CHAR_SET_LEN, IMAGE_HEIGHT, IMAGE_WIDTH, MAX_ACCURACYfrom gen_image import gen_require_captcha_image&x_input = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])y_input = tf.placeholder(tf.float32, [None, CHAR_SET_LEN * MAX_CAPTCHA])keep_prob = tf.placeholder(tf.float32)&&# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用,对于抽取特征也没啥用)def convert2gray(img):&&&&if len(img.shape) & 2:&&&&&&&&gray = np.mean(img, -1)&&&&&&&&return gray&&&&else:&&&&&&&&return img&&def __weight_variable(shape, stddev=0.01):&&&&initial = tf.random_normal(shape, stddev=stddev)&&&&return tf.Variable(initial)&&def __bias_variable(shape, stddev=0.1):&&&&initial = tf.random_normal(shape=shape, stddev=stddev)&&&&return tf.Variable(initial)&&def __conv2d(x, w):&&&&# strides 代表移动的平长&&&&return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')&&def __max_pool_2x2(x):&&&&return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')&&# 100个一个批次def gen_next_batch(batch_size=100):&&&&batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])&&&&batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])&&&&&for i in xrange(batch_size):&&&&&&&&text, image = gen_require_captcha_image()&&&&&&&&&# 转成灰度图片,因为颜色对于提取字符形状是没有意义的&&&&&&&&image = convert2gray(image)&&&&&&&&&batch_x[i, :] = image.flatten() / 255&&&&&&&&batch_y[i, :] = text_to_array(text)&&&&&return batch_x, batch_y&&def create_layer(x_input, keep_prob):&&&&x_image = tf.reshape(x_input, shape=[-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1])&&&&&# 定义第1个卷积层&&&&w_c1 = __weight_variable([5, 5, 1, 32], stddev=0.1)&&# 3x3 第一层32个卷积核 采用黑白色&&&&b_c1 = __bias_variable([32], stddev=0.1)&&&&h_c1 = tf.nn.relu(tf.nn.bias_add(__conv2d(x_image, w_c1), b_c1))&&# 定义第一个卷积层&&&&h_pool1 = __max_pool_2x2(h_c1)&&# 定义第一个池化层&&&&# h_pool1 = tf.nn.dropout(h_pool1, keep_prob)&&&&&# 定义第2个卷积层&&&&w_c2 = __weight_variable([5, 5, 32, 64], stddev=0.1)&&&&b_c2 = __bias_variable([64], stddev=0.1)&&&&h_c2 = tf.nn.relu(tf.nn.bias_add(__conv2d(h_pool1, w_c2), b_c2))&&&&h_pool2 = __max_pool_2x2(h_c2)&&&&# h_pool2 = tf.nn.dropout(h_pool2, keep_prob)&&&&&# 定义第3个卷积层&&&&w_c3 = __weight_variable([5, 5, 64, 64], stddev=0.1)&&&&b_c3 = __bias_variable([64], stddev=0.1)&&&&h_c3 = tf.nn.relu(tf.nn.bias_add(__conv2d(h_pool2, w_c3), b_c3))&&&&h_pool3 = __max_pool_2x2(h_c3)&&&&# h_pool3 = tf.nn.dropout(h_pool3, keep_prob)&&&&&# 3层池化之后 width 144 / 8 = 18&&&&# height 64 / 8 = 8&&&&&# 全链接层1&&&&w_fc1 = __weight_variable([20 * 8 * 64, 1024], stddev=0.1)&&&&b_fc1 = __bias_variable([1024])&&&&h_pool3_flat = tf.reshape(h_pool3, [-1, w_fc1.get_shape().as_list()[0]])&&&&h_fc1 = tf.nn.relu(tf.add(tf.matmul(h_pool3_flat, w_fc1), b_fc1))&&&&# drop out 内容0&&&&h_fc1_dropout = tf.nn.dropout(h_fc1, keep_prob)&&&&&# 全链接层2&&&&w_output = __weight_variable([1024, MAX_CAPTCHA * CHAR_SET_LEN], stddev=0.1)&&&&b_output = __bias_variable([MAX_CAPTCHA * CHAR_SET_LEN])&&&&y_output = tf.add(tf.matmul(h_fc1_dropout, w_output), b_output)&&&&&return y_output&&def create_loss(layer, y_input):&&&&loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_input, logits=layer))&&&&return loss&&def create_accuracy(output, y_input):&&&&predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])&&&&max_idx_p = tf.argmax(predict, 2)&&&&max_idx_l = tf.argmax(tf.reshape(y_input, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)&&&&correct_pred = tf.equal(max_idx_p, max_idx_l)&&&&accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))&&&&return accuracy&&def train():&&&&# create the layer and loss&&&&layer_output = create_layer(x_input, keep_prob)&&&&loss = create_loss(layer_output, y_input)&&&&accuracy = create_accuracy(layer_output, y_input)&&&&&train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)&&&&# save model&&&&saver = tf.train.Saver()&&&&&with tf.Session() as sess:&&&&&&&&&tf.global_variables_initializer().run()&&&&&&&&acc = 0.0&&&&&&&&i = 0&&&&&&&&&while acc & MAX_ACCURACY:&&&&&&&&&&&&i = i + 1&&&&&&&&&&&&batch_x, batch_y = gen_next_batch(64)&&&&&&&&&&&&_, _loss = sess.run([train_step, loss],&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&feed_dict={x_input: batch_x, y_input: batch_y, keep_prob: 0.75})&&&&&&&&&&&&&print(i, _loss)&&&&&&&&&&&&&# 每100 step计算一次准确率&&&&&&&&&&&&if i % 50 == 0:&&&&&&&&&&&&&&&&batch_x_test, batch_y_test = gen_next_batch(100)&&&&&&&&&&&&&&&&acc = sess.run(accuracy, feed_dict={x_input: batch_x_test, y_input: batch_y_test, keep_prob: 1.})&&&&&&&&&&&&&&&&print('step is %s' % i, 'and accy is %s' % acc)&&&&&&&&&&&&&&&&# 如果准确率大于50%,保存模型,完成训练&&&&&&&&&&&&&&&&if acc & MAX_ACCURACY:&&&&&&&&&&&&&&&&&&&&print('current acc & %s&&,stop now' % MAX_ACCURACY)&&&&&&&&&&&&&&&&&&&&saver.save(sess, "break.model", global_step=i)&&&&&&&&&&&&&&&&&&&&break&&if __name__ == '__main__':&&&&train()&&
# -*- coding: utf-8 -*-
from gen_model import create_layer
import tensorflow as tf
import config
import numpy as np
from gen_image import convert2gray, gen_random_captcha_image, array_to_text
def crack_captcha(captcha_image):
x_input = tf.placeholder(tf.float32, [None, config.IMAGE_HEIGHT * config.IMAGE_WIDTH])
keep_prob = tf.placeholder(tf.float32)
output = create_layer(x_input, keep_prob)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
predict = tf.argmax(tf.reshape(output, [-1, config.MAX_CAPTCHA, config.CHAR_SET_LEN]), 2)
text_list = sess.run(predict, feed_dict={x_input: [captcha_image], keep_prob: 1})
text = text_list[0].tolist()
vector = np.zeros(config.MAX_CAPTCHA * config.CHAR_SET_LEN)
for n in text:
vector[i * config.CHAR_SET_LEN + n] = 1
return array_to_text(vector)
def validate_image():
text, image = gen_random_captcha_image()
image = convert2gray(image)
# map the value to 0 -& 1 ,this will really affect the loss function update ,always remember the value should
# suit to the loss learning rate
# refer /watch?v=pU5TG_X7b6E&index=6&list=PLwY2GJhAPWRcZxxVFpNhhfivuW0kX15yG 21:00
image = image.flatten() / 255
predict_text = crack_captcha(image)
print("label is : {} &----& predict is : {}".format(text, predict_text))
if __name__ == '__main__':
validate_image()
123456789101112131415161718192021222324252627282930313233343536373839404142434445
# -*- coding: utf-8 -*-from gen_model import create_layerimport tensorflow as tfimport configimport numpy as npfrom gen_image import convert2gray, gen_random_captcha_image, array_to_text&&def crack_captcha(captcha_image):&&&&x_input = tf.placeholder(tf.float32, [None, config.IMAGE_HEIGHT * config.IMAGE_WIDTH])&&&&keep_prob = tf.placeholder(tf.float32)&&# dropout&&&&output = create_layer(x_input, keep_prob)&&&&&saver = tf.train.Saver()&&&&with tf.Session() as sess:&&&&&&&&saver.restore(sess, tf.train.latest_checkpoint('.'))&&&&&&&&predict = tf.argmax(tf.reshape(output, [-1, config.MAX_CAPTCHA, config.CHAR_SET_LEN]), 2)&&&&&&&&text_list = sess.run(predict, feed_dict={x_input: [captcha_image], keep_prob: 1})&&&&&&&&&text = text_list[0].tolist()&&&&&&&&vector = np.zeros(config.MAX_CAPTCHA * config.CHAR_SET_LEN)&&&&&&&&i = 0&&&&&&&&for n in text:&&&&&&&&&&&&vector[i * config.CHAR_SET_LEN + n] = 1&&&&&&&&&&&&i += 1&&&&&&&&&return array_to_text(vector)&&def validate_image():&&&&text, image = gen_random_captcha_image()&&&&image = convert2gray(image)&&&&&# map the value to 0 -& 1 ,this will really affect the loss function update ,always remember the value should&&&&# suit to the loss learning rate&&&&# refer /watch?v=pU5TG_X7b6E&index=6&list=PLwY2GJhAPWRcZxxVFpNhhfivuW0kX15yG 21:00&&&&image = image.flatten() / 255&&&&predict_text = crack_captcha(image)&&&&print("label is : {} &----& predict is : {}".format(text, predict_text))&&if __name__ == '__main__':&&&&validate_image()&&
训练的时间长短和字符长度和训练字符种类完相关,4位纯数字 ,大概4000次以内训练批次,可以达到90% 以上准确率,当然,GPU跑的更快一点
2017年十月
2017年九月
2017年八月
2017年七月
2017年六月
2017年五月
2017年四月
2017年三月
2017年二月
2016年十二月
2016年十一月
2016年十月
2016年九月
2016年八月
2016年五月
2016年四月
2016年三月
2016年二月
2016年一月
2015年十二月
2015年十一月
2015年十月
2015年九月
2015年八月
2015年七月
2015年四月
2015年三月
2014年十一月
2014年九月
2014年五月
2014年四月
2014年三月
2014年二月
2014年一月
2013年五月
2013年四月
2013年三月
2013年二月
2013年一月
2012年十二月
2012年十一月
2012年十月
2012年七月
2012年六月
2012年五月
2012年四月【图片】如何通过Keras来掌握深度学习【技术吧】_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:185,148贴子:
如何通过Keras来掌握深度学习收藏
原文:Learning Deep Learning with Keras 作者: Piotr Migda?
90%相似度,10%成本.3000案例尽在技术服务
本文作者是一位教授深度学习的老师。传授深度学习知识既是他养家糊口的职业(Kaggle比赛获胜队伍的教练),也是他在波兰儿童基金会志愿者工作的一部分。因此,他打算和我们分享一些学习和教授深度学习知识时的心得。本文并不会具体讲解某个神经网络模型,而是总览性的介绍。
首先,不要害怕接触神经网络模型,入门真的很容易!作者当初害怕难学,现在后悔学晚了。我们只要具备最基本的编程知识、简单的数学知识和机器学习概念就可以上手。作者接下来就会介绍如何上手学习。
在他看来,最好的学习方法是从高层次的互动方式切入,因此,他建议学习Keras的图像识别任务,这是Python环境下的一个通用神经网络库,只需几行代码就够。若是想再缩减代码量,唯一的方法就是用鸽子。没错,认真脸:鸽子诊断癌症的水平堪比人类专家
深度学习是什么?深度学习是机器学习技术之一,采用多层神经网络模型。近些年来人们在此领域开展了大量的探索,在视觉识别等领域准确率已经达到人类的水平。不像量子计算、核聚变等,这项技术当前正应用于实际产品中,而不是凭空画大饼。大牛曾经说过:大多数正常人能在一秒之内完成的任务,现在都能由人工智能来完成。
Google和Facebook等公司一直处于技术前沿并不令人感到惊讶。事实上,作者表示每个几个月他都会被某些超出自己期望的技术所征服,比如:循环神经网络的神器效果用于模仿生成莎士比亚作品、维基百科词条和LaTeX文章一种艺术形式迁移的神经算法实时人脸捕捉和重现彩色图像彩色化用于真实感图像生成的即插即用生成网络基于其它医疗诊断技术的专家级皮肤癌分类图片到图片的翻译教授机器学画猫、狗等动物的简笔画
看起来似乎像是一件件魔法。如果大家对神经网络模型感兴趣,可以观看系列入门教程的视频:Stephen Welch的神经网络模型解密J Alammar的神经网络基础指导
这些算法往往需要海量训练数据。下图是逻辑回归、随机森林和深度学习三种方法在Higgs数据集上的AUC分数(横坐标的单位是百万):
一般来说,我们并不能保证深度学习的效果比其它方法好,比如随机森林或者决策树,即使在数据量足够大的情况下。
开始实践是否需要Skynet之类的神器帮助运行呢?显然不必,甚至可以在浏览器内运行代码:TensorFlow Playground提供可视化界面的样本分类ConvNetJS用于数字和图像识别Keras.js Demo在浏览器中可视化展现和使用网络模型
高级技术学校,选北大青鸟中博软件学院,直属北京大学.选好学校学好专业,就到北大青鸟学IT,高端技能在手,薪资待遇不愁!0元入学,先就业后付款,让你放心选择!
如果想要在Python环境中使用Keras,参考这个?/sta?red/keras-mini-exam?ples/blob/ma?ster/mnist_sim?ple.ipynb
Python和机器学习作者之前提到过Python和机器学习是必备的基础知识。相关的教程可以分别参考作者曾经的文章《基于Python的数据科学介绍》以及《统计与机器学习》。
对于Python,如果大家的电脑里已经安装了Anaconda环境,只需再安装TensorFlow和Keras。
至于机器学习,在入坑深度学习之前并不需要掌握太多的相关知识。当然,之后在实践中可以分析某个问题是否能够采取更简单的方法。比如,随机森林算法就是万能钥匙,适用于大部分问题。大家需要理解我们为什么要训练模型,然后测试它的效果。可以参考下面的教程:Stephanie Yee和Tony Chu的《机器学习的可视化介绍》
数学知识深度学习模型中用到的数学知识还算是比较基础。下面罗列了一些,这些知识在其它网络模型里也很常见:向量、矩阵和多维数组;加法和乘法;卷积运算提取局部特征;激活函数:sigmoid, tanh或者ReLU等;softmax将向量转化为概率值;log-loss(cross-entropy)作为惩罚项网络参数优化的梯度反向传播算法随机梯度下降及其变种(比如冲量)
如果大家的学科背景是数学、统计学、物理或者信号处理,那应该绰绰有余了。如果只有高中数学的基础,也别慌。用于识别数字的卷计算机网络也可以仅用Excel表格实现:Deep Spreadsheets with ExcelNet。
向量计算是深度学习和其它机器学习算法的基本内容(比如,作者曾经介绍过word2vec的文章)。作者建议大家参考下面几份学习资料:J. Str?m, K. ?str?m, 和 T. Akenine-M?ller 编写的《Immersive Linear Algebra》应用数学和机器学习基础:《深度学习》的线性代数章节Brendan Fortuner 的《Linear algebra cheat sheet for deep learning 》
以及Numpy相关的一些基础知识:Nicolas P. Rougier 的《From Python to Numpy》《SciPy lectures: The NumPy array object》
框架目前,市面上有很多流行的深度学习库,包括Tensorflow、Theano、Torch和Caffe。它们都提供了Python接口(Torch也开放了Python接口:PyTorch)
我们该如何选择呢?作者建议,首先在标准测试集上跑一遍各个方法的效果,因为过早的优化是万恶之源。最明智的做法是选一个容易开发、在线文档齐全而且安装方便的工具。
这里也有几篇篇幅较短的文章:Erik Reppel写的基于Keras 和 Cats 的卷计算机网络可视化Petar Veli?kovi? 写的深度学习完全入门:基于Keras的卷计算机网络Jason Brownlee写的用Keras和卷计算机网络识别手写数字
(补23楼)Keras如果大家信奉Python的哲学(简洁、易读),Keras正合你意。它属于神经网络的上层封装库,对Tensorflow和Theano做了封装。下图是大家较为认可的各个工具排名:深度学习框架概览,2017年4月,Keras创作者Francois Chollet根据Github评分制作除了Github的活跃度,也可以参考根据arXiv论文得到的排名,参见by Andrej Karpathy的报告《机器学习趋势一瞥》。工具的流行程度越高,意味着如果你遇到了问题,在Google搜索得到答案的机会也越大。Keras的学习文档非常友善,它的官方博客也提供了宝贵的资源。为了全面了解在 jupyter notebook 环境下使用 Keras,作者强烈建议阅读:Valerio Maggio的《基于Keras和Tensorflow的深度学习》
另外,作者还开发了许多非常实用的Keras插件。比如查看序列模型网络内部数据流的ASCII summary,比model.summary()用起来更方便。它可以显示层级、数据维度以及待优化的参数数量。例如,一个数字识别网络是这样的:
DATA DIMENSIONS
WEIGHTS(N)
WEIGHTS(%)
-------------------
-------------------
MaxPooling2D
Y max -------------------
| || -------------------
-------------------
-------------------
MaxPooling2D
Y max -------------------
| || -------------------
||||| -------------------
XXXXX -------------------
| || -------------------
XXXXX -------------------
Tensorflow如果不用Keras,作者则建议只用Tensorflow。它比Keras更底层、更灵活,能直接对各个多维数组参数做优化。下面也是作者推荐的一些相关资源:官方教程Tensorflow Tutorial非常不错Martin G?rner 的《不读博士也能学习Tensorflow和深度学习》Aymeric Damien 写的《Tensorflow入门教程和示例》Nathan Lintz 写的《Tensorflow框架简单教程》另外,TensorBoard是一款在训练过程中调试和查看数据非常方便的工具。
其它Theano与Tensorflow很相似,但是更早出现,略微难以上手。比如,大家需要自己动手写变量更新的代码。不提供典型的神经网络层级,往往还需要再调用lasagne包。作者也推荐了入门教程:Marek Rei编写的Theano教程
数据集解决每个机器学习问题都离不开数据。我们没办法告诉计算机“检测图片中是否有猫”这个命令,希望计算机直接给我们答案。而是要提供大量含有猫和不含有猫的图片,然后让计算机从这些数据中学习。因此,我们手头必须要先有一份数据集。这并不是机器学习或是深度学习的短板,任何的学习方法都离不开数据!
作者推荐了几个常用的数据集。它们的共同点就是……常用!这就意味着大家很容易在网上找到可以运行的示例,并且前人已经留下了大量的经验。
MNIST很多好的想法在MNIST数据集上并不管用(比如batch norm)。相反,很多糟糕的想法对MNIST有效,但是却无法迁移到实际问题中。—— 摘自[Fran?ois Chollet 的推特](r.com/fchollet/status/)
MNIST是一份手写数字识别数据集(6的灰度图)。它适合用来测试本机上安装的Keras是否成功。
notMNIST其实,我曾经说过,AI研究者面临的最难回答的问题就是“字母A和I是什么?” —— [Douglas R. Hofstadter](ord.edu/group/SHR/4-2/text/hofstadter.html)(1995年)
登录百度帐号推荐应用

我要回帖

 

随机推荐