检查目标时出错:预期dense_Dense2 的形状为x,但数组的形状为y [英] Error when checking target: expected dense_Dense2 to have shape x, but got array with shape y

查看:43
本文介绍了检查目标时出错:预期dense_Dense2 的形状为x,但数组的形状为y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 tensorflow 中的第一步.

It is my first steps in the tensorflow.

想法

有一些数字模式(数字数组:Pattern = number[]).以及与此模式对应的类别(从 0 到 2 的数字:Category = 0 | 1 | 2).我遵循结构数据:xs = Pattern[], ys = Category[].

There is some pattern of numbers (the array of numbers: Pattern = number[]). And the category that corresponds to this pattern (the number from 0 to 2: Category = 0 | 1 | 2). I have follow the structure data: xs = Pattern[], ys = Category[].

例如:

xs = [[1, 2, 3, 4], [5, 6, 7, 8], ..., [9, 10, 11, 12]];
ys = [1, 0, ..., 2];

我希望神经网络在 xs[0]xy[0] 之间找到匹配,依此类推.我想像[1, 2, 3, 4]一样传递神经网络数据,得到接近1的结果.

I want the neural network to find a match between xs[0] and xy[0], and so on. I want to pass the neural network data like [1, 2, 3, 4] and get a result close to 1.

model.predict(tf.tensor([1, 2, 3, 4])) // ≈1

我的代码

import * as tf from '@tensorflow/tfjs';
require('@tensorflow/tfjs-node');

const xs = tf.tensor2d([
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
]);
const ys = tf.tensor1d([0, 1, 2]);

const model = tf.sequential();
model.add(tf.layers.dense({ units: 4, inputShape: xs.shape, activation: 'relu' }));
                                   ^ - Pattern length, it is constant
model.add(tf.layers.dense({ units: 3, activation: 'softmax' }));
model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] });

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

我收到以下错误:

检查输入时出错:预期dense_Dense1_input 有3 个维度.但是得到了形状为 3,4 的数组

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

我不明白如何解释我的神经网络数据结构.

I don't understand how to explain my data structure for the neural network.

推荐答案

我找到了适合我的任务的解决方案.只需要使用dataset

I found the right solution for my task. Just need to use the dataset

https://js.tensorflow.org/api/latest/#tf.Sequential.fitDataset

import * as tf from '@tensorflow/tfjs';
require('@tensorflow/tfjs-node');

const xArray = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
];

const yArray = [0, 1, 2];
const { length } = yArray;

const xs = tf.data.array(xArray);
const ys = tf.data.array(yArray);

const xyDataset = tf.data.zip({ xs: xDataset, ys: yDataset }).batch(length).shuffle(length);

const model = tf.sequential();
model.add(tf.layers.dense({ units: length, inputShape: [length], activation: 'relu' }));
model.add(tf.layers.dense({ units: 3, activation: 'softmax' }));
model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] });

model.fitDataset(xyDataset, { epochs: 500 });

这篇关于检查目标时出错:预期dense_Dense2 的形状为x,但数组的形状为y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆