Ошибка при проверке входных данных: ожидается, что dens_Dense5_input имеет 4 измерения. но получил массив с формой 5,2,5

1

Я изучаю tensorflow.js, и я пытался создать модель, которая будет прогнозировать победителя случайного матча/игры между 2 "командами" на основе их "игроков".

const rawMatches = [
  {
    t1: [2, 99, 3, 5, 7],
    t2: [4, 75, 48, 23, 6],
    winner: 0
  },
  {
    t1: [2, 99, 48, 5, 7],
    t2: [4, 75, 3, 23, 6],
    winner: 1
  },
  {
    t1: [2, 83, 3, 4, 23],
    t2: [4, 75, 58, 25, 78],
    winner: 0
  },
  {
    t1: [26, 77, 11, 5, 7],
    t2: [3, 43, 48, 23, 9],
    winner: 1
  },
  {
    t1: [2, 99, 3, 5, 7],
    t2: [6, 65, 28, 23, 6],
    winner: 0
  }
];

const train = async () => {
  //   [
  //     [[2, 99, 3, 5, 7], [4, 75, 48, 23, 6]],
  //     [[2, 99, 48, 5, 7], [4, 75, 3, 23, 6]],
  //     [[2, 99, 3, 5, 7], [4, 75, 48, 23, 6]]
  //   ];
  const xs = tf.tensor3d(
    rawMatches.map((match, index) => [match.t1, match.t2])
  );

  //   [[1, 0], [0, 1], [1, 0]];
  const labelsTensor = tf.tensor1d(
    rawMatches.map(match => (match.winner === 1 ? 1 : 0)),
    "int32"
  );

  const ys = tf.oneHot(labelsTensor, 2);

  xs.print();
  ys.print();

  let model = tf.sequential();
  const hiddenLayer = tf.layers.dense({
    units: 15,
    activation: "sigmoid",
    inputShape: [5, 2, 5]
  });
  const outputLayer = tf.layers.dense({
    units: 2,
    activation: "softmax"
  });
  model.add(hiddenLayer);
  model.add(outputLayer);

  const optimizer = tf.train.sgd(0.2);

  model.compile({
    optimizer,
    loss: "categoricalCrossentropy"
  });

  model.fit(xs, ys, { epochs: 1 });
};

train();
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>

После того, как вы попытаетесь установить модель, возникают такие ошибки:

Error when checking input: expected dense_Dense11_input to have 4 dimension(s). but got array with shape 5,2,5

Текстовая песочница с полным кодом: https://codesandbox.io/s/kr37m63w7

Теги:
tensorflow
machine-learning
tensorflow.js

1 ответ

1
Лучший ответ

Существует две проблемы с этой моделью:

Сначала измерение входного сигнала x передается методу fit. xs должен быть на один размер выше, чем первый inputShape. Поскольку xs - это массив, содержащий данные формы inputShape, inputShape должен быть [2, 5].

Во-вторых, поскольку размер входных и выходных данных не соответствует, вам нужно использовать tf.flatten для изменения размера данных. Оба размера не совпадают, так как форма входных данных [2, 5] (size = 2) тогда как форма выходных данных [2] (size = 1)

const rawMatches = [
  {
    t1: [2, 99, 3, 5, 7],
    t2: [4, 75, 48, 23, 6],
    winner: 0
  },
  {
    t1: [2, 99, 48, 5, 7],
    t2: [4, 75, 3, 23, 6],
    winner: 1
  },
  {
    t1: [2, 83, 3, 4, 23],
    t2: [4, 75, 58, 25, 78],
    winner: 0
  },
  {
    t1: [26, 77, 11, 5, 7],
    t2: [3, 43, 48, 23, 9],
    winner: 1
  },
  {
    t1: [2, 99, 3, 5, 7],
    t2: [6, 65, 28, 23, 6],
    winner: 0
  }
];

const train = () => {
  const xs = tf.tensor3d(
    rawMatches.map((match, index) => [match.t1, match.t2])
  );
  const labelsTensor = tf.tensor1d(
    rawMatches.map(match => (match.winner === 1 ? 1 : 0)),
    "int32"
  );

  const ys = tf.oneHot(labelsTensor, 2);

  xs.print();
  ys.print();

  let model = tf.sequential();
  const hiddenLayer = tf.layers.dense({
    units: 15,
    activation: "sigmoid",
    inputShape: [2, 5]
  });
  const outputLayer = tf.layers.dense({
    units: 2,
    activation: "softmax"
  });
  model.add(hiddenLayer);
  model.add(tf.layers.flatten())
  model.add(outputLayer);

  const optimizer = tf.train.sgd(0.2);

  model.compile({
    optimizer,
    loss: "categoricalCrossentropy"
  });

  model.fit(xs, ys, { epochs: 1 });
};

train();
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню