2017-05-10 2 views
0

몇 년 동안 코딩하지 않았지만 용서해주십시오. 불가능한 일을하려고합니다. 저는 같은 기본 동작을하는 38 명의 비디오를 가지고 있습니다. 나는 올바른 일을하는 사람들을 식별하기 위해 모델을 훈련시키고 싶다. 그레이 스케일이 작동하지 않아서 사용한 예제처럼 테스트하고 싶었 기 때문에 지금은 컬러를 사용하고 있습니다. 나는 an example, link에 정의 된 모델을 사용했다.Keras 모델 ValueError : 모델 타겟을 검사 할 때 오류가 발생했습니다.

Keras, 아나콘다 (64) Python3.5, Tensorflow 백엔드, 윈도우 10 (64 비트)에

나는이 문제에 다른 모델을 시도하고 메모리를 줄이기 위해 그레이 스케일을 사용하는 기대했다, 그러나 과거를 얻을 어차피

첫 번째 단계!

감사합니다 !!!

import time 
import numpy as np 
import sys 
import os 
import cv2 
import keras 
import tensorflow as tf 

from keras.models import Sequential 
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization 
from keras.layers import Conv3D, Conv2D, MaxPooling2D, GRU, ConvLSTM2D, TimeDistributed 


y_cat = np.zeros(40,np.float) 
good = "Good" 
bad = "Bad" 


batch_size = 32 
num_classes = 1 
epochs = 1 
nvideos = 38 
nframes = 130 
nrows = 240 
ncols = 320 
nchan = 3 

x_learn = np.zeros((nvideos,nframes,nrows,ncols,nchan),np.int32) 
x_learn = np.load(".\\train\\datasetcolor.npy") 

with open(".\\train\\tags.txt") as ft: 
    y_learn = ft.readlines() 
y_learn = [x.strip() for x in y_learn] 
ft.close() 

# transform string tags to numeric. 
for i in range (0,len(y_learn)): 
    if (y_learn[i] == good): y_cat[i] = 1 
    elif (y_learn[i] == bad): y_cat[i] = 0 


#build model 
# duplicating from https://github.com/fchollet/keras/blob/master/examples/conv_lstm.py 
model = Sequential() 
model.image_dim_ordering = 'tf' 
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), 
        input_shape=(nframes,nrows,ncols,nchan), 
        padding='same', return_sequences=True)) 
model.add(BatchNormalization()) 
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), 
        padding='same', return_sequences=True)) 
model.add(BatchNormalization()) 

model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), 
        padding='same', return_sequences=True)) 
model.add(BatchNormalization()) 

model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3), 
        padding='same', return_sequences=True)) 
model.add(BatchNormalization()) 

model.add(Conv3D(filters=1, kernel_size=(3, 3, 3), 
       activation='sigmoid', 
       padding='same', data_format='channels_last')) 
model.compile(loss='binary_crossentropy', optimizer='adadelta') 


print(model.summary()) 

# fit with first 3 videos because I don't have the horsepower yet 
history = model.fit(x_learn[:3], y_learn[:3], 
       batch_size=batch_size, 
       epochs=epochs) 

print (history) 

결과 : 여기

내 코드입니다


Layer (type)     Output Shape    Param # 
================================================================= 
conv_lst_m2d_5 (ConvLSTM2D) (None, 130, 240, 320, 40) 62080  
_________________________________________________________________ 
batch_normalization_5 (Batch (None, 130, 240, 320, 40) 160  
_________________________________________________________________ 
conv_lst_m2d_6 (ConvLSTM2D) (None, 130, 240, 320, 40) 115360  
_________________________________________________________________ 
batch_normalization_6 (Batch (None, 130, 240, 320, 40) 160  
_________________________________________________________________ 
conv_lst_m2d_7 (ConvLSTM2D) (None, 130, 240, 320, 40) 115360  
_________________________________________________________________ 
batch_normalization_7 (Batch (None, 130, 240, 320, 40) 160  
_________________________________________________________________ 
conv_lst_m2d_8 (ConvLSTM2D) (None, 130, 240, 320, 40) 115360  
_________________________________________________________________ 
batch_normalization_8 (Batch (None, 130, 240, 320, 40) 160  
_________________________________________________________________ 
conv3d_1 (Conv3D)   (None, 130, 240, 320, 1) 1081  
================================================================= 
Total params: 409,881.0 
Trainable params: 409,561 
Non-trainable params: 320.0 
_________________________________________________________________ 
None 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-3-d909d285f474> in <module>() 
    82 history = model.fit(x_learn[:3], y_learn[:3], 
    83    batch_size=batch_size, 
---> 84    epochs=epochs) 
    85 
    86 print (history) 

ValueError: Error when checking model target: expected conv3d_1 to have 5 dimensions, but got array with shape (3, 1) 

답변

2

"대상" 문제가의 형식에 대 모델의 출력에 있음을 의미 y_learn. 이 모델은 "추측"출력 때문에 y_learn는 "정답"동안

배열 y_learn는 정확히 모델의 출력 같은 형상이어야한다. 시스템은 동일한 치수를 가진 경우에만 추측을 정답과 비교할 수 있습니다.

  • 모델의 출력 (요약에서 볼 수) : (None,130,240,320,1)
  • y_learn :

    차이를 참조 (None,1) "없음"이 배치 크기입니다

. y_learn [: 3]을주었습니다.이 트레이닝 세션의 배치 크기는 3입니다.

올바르게 수정하려면 y_learn이 무엇인지 이해해야합니다.
잘 이해하면 각 동영상에 대해 0 또는 1의 숫자 만 표시됩니다. 그렇다면 y_learn은 완전히 정상이며, 필요한 것은 모델이 (None,1)과 같은 것을 출력하는 것입니다.

• 그래도 작업을 수행하는 매우 간단한 방법 (최선을 아마도하지, 나는 ... 여기에 더 도움이 될 수없는 것은) 하나 개의 뉴런으로 최종 고밀도 레이어를 추가하는 것입니다

model.add(Flatten()) 
model.add(Dense(1, activation='sigmoid')) 

이제 model.summary()을 수행하면 최종 출력이 (None,1)

+0

으로 표시됩니다. 대단히 감사합니다. – DSP209

+0

귀하의 질문에 대답 한 경우 올바른 답변임을 표시하는 체크 표시를 고려하십시오. :) –

관련 문제