TensorFlow ValueError:维度必须相等

时间:2021-02-17 17:55:21

标签: tensorflow machine-learning keras

我的特征是 4000 维 float32 向量,我的标签是 8000 维 float32 向量。当我尝试训练我的模型时,我显然遇到了尺寸不匹配的问题,但我看不到哪里。

def get_audio_samples_as_tensor(filepath, num_desired_samples=-1):
  audio_binary = tf.io.read_file(filepath) # Decodes a 16-bit PCM WAV file to a float32 tensor.
  tensor, number_of_samples = tf.audio.decode_wav(audio_binary, desired_samples=num_desired_samples)
  tensor = tf.squeeze(tensor, axis=-1) # remove last dimension (representing number of channels). Resulting shape: (None,)
  return tensor

def get_truth_and_labelled_tensors(filename):
  truth_filepath = tf.convert_to_tensor(TRUTH_DIR) + os.sep + filename
  labelled_filepath = tf.convert_to_tensor(DOWNSCALED_DIR) + os.sep + filename

  truth_audio_samples_tensor = get_audio_samples_as_tensor(truth_filepath, num_desired_samples=8000)
  labelled_audio_samples_tensor = get_audio_samples_as_tensor(labelled_filepath, num_desired_samples=4000)
  print("truth_audio_samples_tensor shape: ", truth_audio_samples_tensor.shape) # (8000,)
  print("labelled_audio_samples_tensor shape: ", labelled_audio_samples_tensor.shape) # (4000,)
  
  return labelled_audio_samples_tensor, truth_audio_samples_tensor

train_filenames_ds = tf.data.Dataset.from_tensor_slices(train_filenames)
train_waveforms_ds = train_filenames_ds.map(get_truth_and_labelled_tensors, num_parallel_calls=tf.data.AUTOTUNE)

validation_filenames_ds = tf.data.Dataset.from_tensor_slices(validation_filenames)
validation_waveforms_ds = validation_filenames_ds.map(get_truth_and_labelled_tensors, num_parallel_calls=tf.data.AUTOTUNE)

model = models.Sequential([
  layers.Input(shape=(4000,1)),
  layers.Dense(units=8000),
])

model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['accuracy'])

history = model.fit(train_waveforms_ds,
                    validation_data=validation_waveforms_ds,
                    epochs=10)
Epoch 1/10
WARNING:tensorflow:Model was constructed with shape (None, 4000, 1) for input KerasTensor(type_spec=TensorSpec(shape=(None, 4000, 1), dtype=tf.float32, name='input_17'), name='input_17', description="created by layer 'input_17'"), but it was called on an input with incompatible shape (4000, 1, 1).
ValueError: Dimensions must be equal, but are 8000 and 4000 for '{{node Equal}} = Equal[T=DT_FLOAT, incompatible_shape_error=true](ExpandDims_1, Cast_1)' with input shapes: [8000,1], [4000,1].```

1 个答案:

答案 0 :(得分:0)

您必须如下所示重塑张量。

labelled_audio_samples_tensor = tf.reshape(labelled_audio_samples_tensor , [batch_size, 4000, 1] 

truth_audio_samples_tensor = tf.reshape(truth_audio_samples_tensor, [batch_size, 8000]

评论后更新:

如果是这种情况,您是否可以应用 tf.expand_dims 来重塑您的张量,如下所示?

enter image description here