ypwhs / captcha_break

验证码识别
MIT License
2.73k stars 684 forks source link

Input 0 is incompatible with layer dense_3: expected ndim=2, found ndim=3 #1

Open keviswang opened 7 years ago

keviswang commented 7 years ago

In this place, I got the error: 13 x = Reshape(target_shape=(int(conv_shape[1]), int(conv_shape[2]*conv_shape[3])))(x) 14 ---> 15 x = Dense(32, activation='relu')(x) 16 17 gru_1 = GRU(rnn_size, return_sequences=True, init='he_normal', name='gru1')(x)

ypwhs commented 7 years ago

我无法重现这个错误,我使用的是 keras 1.2.2 和 tensorflow 1.0.1。你可以尝试升级版本。

I can not reproduce this error, I am using keras 1.2.2 and tensorflow 1.0.1.You can try to upgrade the version.

fanyiaa commented 7 years ago

请问用的Python版本是哪一个?

Sqrt5 commented 7 years ago

使用的python是Anaconda4.2.0,keras2.0.8,tensorflow1.3.0 修改成一下没有警告的版本后运行没问题,收敛的也不错,大赞作者

from captcha.image import ImageCaptcha
import matplotlib.pyplot as plt
import numpy as np
import random
import string

characters = string.digits + string.ascii_uppercase
width, height, n_len, n_class = 170, 80, 4, len(characters)
def gen(batch_size=32):
    X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
    y = [np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)]
    generator = ImageCaptcha(width=width, height=height)
    while True:
        for i in range(batch_size):
            random_str = ''.join([random.choice(characters) for j in range(4)])
            X[i] = generator.generate_image(random_str)
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1
        yield X, y
def decode(y):
    y = np.argmax(np.array(y), axis=2)[:,0]
    return ''.join([characters[x] for x in y])
X, y = next(gen(1))
plt.imshow(X[0])
plt.title(decode(y))
from keras.models import *
from keras.layers import *
input_tensor = Input((height, width, 3))
x = input_tensor
for i in range(4):
    x = Conv2D(filters=32*2**i, kernel_size=(3, 3), activation='relu')(x)
    x = Conv2D(filters=32*2**i, kernel_size=(3, 3), activation='relu')(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = [Dense(n_class, activation='softmax', name='c%d'%(i+1))(x) for i in range(4)]
model = Model(inputs=input_tensor, outputs=x)
model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])
from keras.utils.vis_utils import plot_model
plot_model(model, to_file="model.png", show_shapes=True)
model.fit_generator(gen(), steps_per_epoch=1600, epochs=5, validation_data=gen(), validation_steps=40)