首页 > 解决方案 > 为什么 TensorFlow 会抛出这个异常?

问题描述

我有Console Application一个Visual Studio Community 2019带有.NET 5.0. 我正在使用这个TensorFlow.NET

项目文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="SciSharp.TensorFlow.Redist" Version="2.5.0" />
    <PackageReference Include="TensorFlow.Keras" Version="0.5.1" />
    <PackageReference Include="TensorFlow.NET" Version="0.40.1" />
  </ItemGroup>

</Project>

基本上我试图从一组数字中预测数字。

程序.CS:

using System;
using NumSharp;
using static Tensorflow.KerasApi;

namespace TensorFlowTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var trainData = np.array(10f, 20f, 30f, 40f, 50f);
            var trainLabel = np.array(1f, 1f, 1f, 2f, 2f);

            var model = keras.Sequential();
            model.add(keras.layers.Dense(units: 1, activation: null, input_shape: 1));
            model.compile(loss: keras.losses.MeanSquaredError(), optimizer: keras.optimizers.Adam(), metrics: new[] { "acc" });
            model.summary();
            model.fit(trainData, trainLabel, epochs: 300);

            var unseenData = np.array(15f, 25f, 35f, 45f, 55f);
            var prediction = model.predict(unseenData);
            Console.WriteLine(prediction);
        }
    }
}

总结输出为:

Model: sequential
_________________________________________________________________
Layer (type)                  Output Shape              Param #
=================================================================
dense_input (InputLayer)      (None, 1)                 0
_________________________________________________________________
dense (Dense)                 (None, 1)                 2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
_________________________________________________________________

model.fit()工作并训练模型,但是该var prediction = model.predict(unseenData);行引发以下异常:Tensorflow.InvalidArgumentError: 'In[0] and In[1] has different ndims: [5] vs. [1,1]'

如何解决这个问题?

标签: tensorflowkerastensorflow2.0tf.keras

解决方案


推荐阅读