저는 Keras (Theano 백엔드)를 사용하여 chacter 기반 rnn 모델을 구축하고 있습니다. 한 가지 유의할 것은 미리 작성된 손실 함수를 사용하고 싶지 않다는 것입니다. 대신 일부 데이터 포인트의 손실을 계산하려고합니다. 여기에 의미하는 바가 있습니다.Theano의 슬라이스 3-d 텐서
벡터화 된 학습 세트 및 그 레이블은 다음과 같습니다. X_train = np.array ([[0,1,2,3,4]] y_train = np.array ([[1,2,3, 4,5]])
하지만 y_train의 첫 번째 k 요소를 어떤 이유로 든 0으로 대체했습니다. 따라서, 예를 들어, 새로운 y_train는
y_train np.array = ([0,0,3,4,5])
I 0 처음 두 요소를 설정하는 이유는 I이다 돈 손실을 계산할 때 이들을 포함하고 싶지 않습니다. 즉, X_train [2 :]과 y_train [2 :] 사이의 손실을 계산하려고합니다.
여기 내 시도입니다. 라인 35에서 잘못된 paranthesis 마지막 줄에 잘못된 변수 이름과 같은 사소한 오류에서
import numpy as np
np.random.seed(0) # for reproducibility
from keras.preprocessing import sequence
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Embedding
from keras.layers import LSTM
from keras.layers.wrappers import TimeDistributed
X_train = np.array([[0,1,2,3,4]])
y_train = np.array([[0,0,3,4,5]])
y_3d = np.zeros((y_train.shape[0], y_train.shape[1], 6))
for i in range(y_train.shape[0]):
for j in range(y_train.shape[1]):
y_3d[i, j, y_train[i,j]] = 1
model = Sequential()
model.add(Embedding(6, 5, input_length=5, dropout=0.2))
model.add(LSTM(5, input_shape=(5, 12), return_sequences=True) )
model.add(TimeDistributed(Dense(6))) #output classes =6
model.add(Activation('softmax'))
from keras import backend as K
import theano.tensor as T
def custom_objective(y_true,y_pred):
# Find the last index of minimum value in y_true, axis=-1
# For example, y_train = np.array([[0,0,3,4,5]]) in my example, and
# I'd like to calculate the loss only between X_train[3:] and y_train[3:] because the values
# in y_train[:3] (i.e.0) are dummies. The following is pseudo code if y_true is 1-d numpy array, which is not true.
def rindex(y_true):
for i in range(len(y_true), -1, -1):
if y_true(i) == 0:
return i
starting_point = rindex(y_true)
return K.categorical_crossentropy(y_pred[starting_point:], y_true[starting_point:])
model.compile(loss=custom_objective,
optimizer='adam',
metrics=['accuracy'])
model.fit(X_train, y_t, batch_size=batch_size, nb_epoch=1)
그리고 문제의 원인을 설명해 주시겠습니까? – malioboro
함수 "custom_objective"가 작동하지 않습니다. – user1610952