#python #tensorflow
Вопрос:
Я сделал этот колаб, чтобы вы могли поиграть с кодом.
tldr; Форма my x_data
есть (# of examples, 12, 1, 100, 1 )
, и когда данные передаются в модель, форма каждого примера становится (None, 12, 1, 100, 1 )
. Как мне избавиться от «Нет»?
Я пытаюсь обучить серию примеров со следующей структурой данных:
import numpy as np
x_train = np.reshape(np.random.rand(200, 12, 100),(200, 12, 1, 100, 1)) #X training data (see dimensions in output)
y_train = np.random.rand(200, 20) #Y training data (see dimensions in output)
n_class = np.shape(y_train)[1] #Number of classes in the classification task
print(np.shape(x_train))
print(np.shape(y_train))
____________
(200, 12, 1, 100, 1)
(200, 20)
размеры x_train объяснены:
- Есть 200 примеров. Каждый пример x_train имеет соответствующий пример y_train с вектором 20 dim, закодированным в одну горячую, представляющим класс, к которому он принадлежит.
- Каждый пример содержит 12 временных рядов. Каждый временной ряд имеет длину 100 единиц, и мы хотим свернуть их отдельно.
- Мы сформировали каждый временной ряд как (1, 100, 1) из-за документации Conv1D keras.
- Согласно приведенной выше ссылке, входные размеры должны быть: (размер пакета, (шаги, input_dim))
размер пакета = 1, шаги = 100, input_dim = 1
Модель выглядит следующим образом (ее также можно найти в colab):
def custom_model(x_data, n_class):
"""
This is the custom model used to convolve over the data
We want to convolve over each dimension independently
"""
conv_inputs = []
conv_outputs = []
amount_of_filters = np.shape(x_data[0])[0]
# Let's create a separate convolution channel for each one of the dims in x_data
for i in range(amount_of_filters):
x0 = keras.Input(batch_shape=(1, 100, 1))
# conv_inputs will therefore have a size of (12, 1, 100, 1)
conv_inputs.append(x0)
x0 = Conv1D(filters=20,kernel_size=10,strides=2,padding="same",data_format="channels_last")(x0)
x0 = MaxPool1D(pool_size=6, data_format="channels_last")(x0)
x0 = Conv1D(filters=20, kernel_size=4, padding="same", data_format="channels_last")(x0)
x0 = MaxPool1D(pool_size=3, data_format="channels_last", padding="same")(x0)
x0 = Flatten()(x0)
x0 = Dense(100, activation="relu")(x0)
x0 = Dropout(0.2)(x0)
x0 = Dense(10, activation="relu")(x0)
conv_outputs.append(x0)
# Convolving all outputs from the above convolutions.
x1 = concatenate(conv_outputs)
x1 = Dense(100, activation="relu")(x1)
x1 = Dense(100, activation="relu")(x1)
out = Dense(n_class)(x1)
modelConv = keras.Model(inputs=conv_inputs, outputs=out)
return modelConv
При запуске модели:
model = custom_model(x_train, n_class)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=250, verbose=1, shuffle=True)
The following error comes up:
ValueError: Layer model expects 12 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 12, 1, 100, 1) dtype=float32>]
You can see that the input shape is (None, 12, 1, 100, 1 ). How do I get rid of the None? As shown above, when printing the shape of x_train, the None dimension does not appear.
My question is how do I feed in the x_data with each example being (12, 1, 100, 1) dimensional?
Thank you!