我正在建立一個使用Keras(Theano後端)的基於chacter的rnn模型。有一點要注意的是我不想使用預先構建的丟失函數。相反,我想計算一些數據點的損失。這是我的意思。Theano的切片三維張量
Vectoried訓練集和其標籤看起來像這樣: X_train = np.array([[0,1,2,3,4]]) y_train = np.array([[1,2,3, 4,5]])
但我用y替換了y_train中的第一個k元素,出於某種原因。因此,舉例來說,新y_train是
y_train = np.array([[0,0,3,4,5]])
爲什麼前兩個元素設置爲0的原因是我不在計算丟失時不想包含它們。換句話說,我想計算X_train [2:]和y_train [2:]之間的損失。
這是我的嘗試。
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