8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

如何将输入 0 与我的层密集对齐

Mike Vine 2月前

43 0

我正在尝试将一些输入传递到几个层,但似乎我的输入形状在某个地方未对齐,以致于它无法正确地穿过层,从而引发值错误,因为

我正在尝试将一些输入传递到几个层,但似乎我的输入形状在某处未对齐,以致它无法正确地穿过各层,从而引发如下值错误:

以下是回溯错误:

Traceback (most recent call last):
  File "c:\Users\USER\CODE\PycharmProjects\pythonProject2Conda\main5.py", line 52, in <module>
    model.evaluate(ds_test)
  File "C:\Users\USER\anaconda3\envs\tf_cpu\Lib\site-packages\keras\src\utils\traceback_utils.py", line 123, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\USER\anaconda3\envs\tf_cpu\Lib\site-packages\keras\src\layers\input_spec.py", line 227, in assert_input_compatibility
    raise ValueError(
ValueError: Exception encountered when calling Sequential.call().

Input 0 of layer "dense" is incompatible with the layer: expected axis -1 of input shape to have value 25088, but received input with shape (28, 896)

Arguments received by Sequential.call():
  • inputs=tf.Tensor(shape=(28, 28, 1), dtype=float32)
  • training=False
  • mask=None

这是代码主体

(ds_train, ds_test), ds_info = tfds.load(
    "mnist",
    split=["train", "test"],
    shuffle_files=True,
    as_supervised=True,
    with_info=True
)

def normalize_img(image, label):
    return tf.cast(image, tf.float32)/255.0, label

AUTOTUNE = tf.data.experimental.AUTOTUNE
BATCH_SIZE = 64

ds_train = ds_train.map(normalize_img, num_parallel_calls=AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits["train"].num_examples)
ds_train = ds_train.batch(BATCH_SIZE)
ds_train = ds_train.prefetch(AUTOTUNE)

ds_test = ds_test.map(normalize_img, num_parallel_calls=AUTOTUNE)
de_test = ds_test.batch(128)
ds_test = ds_test.prefetch(AUTOTUNE)

model = keras.Sequential ([
    keras.Input(shape=[28, 28, 1],),
    layers.Conv2D(32, 3, activation='relu', padding="same"),
    layers.Flatten(),
    layers.Dense(10),

])

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=0.001),
    loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"],

)

model.fit(ds_train, epochs=5, verbose=2)
model.evaluate(ds_test)

ValueError: Exception encountered when calling Sequential.call().

Input 0 of layer "dense" is incompatible with the layer: expected axis -1 of input shape to have value 25088, but received input with shape (28, 896)                            to have value 25088, but received input with shape (28, 896)

Arguments received by Sequential.call():
  • inputs=tf.Tensor(shape=(28, 28, 1), dtype=float32)
  • training=False
  • mask=None

请帮忙

帖子版权声明 1、本帖标题:如何将输入 0 与我的层密集对齐
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Mike Vine在本站《tensorflow》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 我从教程中复制了这段代码,将 tensorflow 导入为 tf,将 tensorflow_datasets 导入为 tfds,导入 osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'setattr(tfds.image_classification。

    我已经从教程中复制了此代码

    import tensorflow as tf
    import tensorflow_datasets as tfds
    import os
    
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    
    setattr(tfds.image_classification.cats_vs_dogs, 
    '_URL',"https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368- 
    6DEBA77B919F/kagglecatsanddogs_5340.zip")
    datos, metadatos = tfds.load('cats_vs_dogs', as_supervised = True, with_info = True)
    

    \'档案中没有名为'PetImages\\Cat\\0.jpg'的项目\'文件\'C:\Users\Timaure\Documents\AI T\AI T.py\',第 8 行,在 datos 中,metadatos = tfds.load('cats_vs_dogs', as_supervised = True, with_info = True)KeyError: \'档案中没有名为'PetImages\\Cat\\0.jpg'的项目\'

    我遇到了这个错误,我是张量和 AI 的新手,在初始行 xx 中遇到了错误,我在网上复制了错误,但没有找到解决方案。我该如何修复它?

  • 我有以下 JSON 字符串:{ \'results\':[ { \'id\':11, \'name\':\'Employee A\', \'isEmployee\':true }, { \'id\':12, \'name\':\'Empl...

    我有以下 JSON 字符串:

    {  
       "results":[  
          {  
             "id":11,
             "name":"Employee A",
             "isEmployee":true
          },
          {
             "id":12,
             "name":"Employee B",
             "isEmployee":true
          },
          {
             "id":13,
             "name":"Employee C",
             "isEmployee":true
          },
          {
             "id":14,
             "name":"Contractor A",
             "isEmployee":false
          },
          {
             "id":15,
             "name":"Contractor B",
             "isEmployee":false
          }
       ],
       "totalItems":5
    }
    

    我需要从中删除 id 和 isEmployee 属性并仅保留 name 属性。

    期望结果如下:

    {  
       "results":[  
          {  
             "name":"Employee A"
          },
          {  
             "name":"Employee B"
          },
          {  
             "name":"Employee C"
          },
          {  
             "name":"Contractor A"
          },
          {  
             "name":"Contractor B"
          }
       ],
       "totalItems":5
    }
    

    如何使用 Newtonsoft JSON.NET 在 C# 中完成此操作?

  • 有两种基本方法,

    任何一个

    或者

    • 将 JSON 反序列化为 不带 附加属性的强类型对象。C# 类型中不存在的属性将被默默删除。然后序列化刚刚反序列化的对象。
  • 我使用了上面提到的第二种方法(反序列化为模仿 JSON 结构的 C# 对象,然后序列化为 JSON),效果很好。

  • 我正在尝试在图像数据集上训练 CNN 模型,但无法获得 TruePositives、TrueNegatives、FalsePositives 和 FalseNegatives 的十进制值。这怎么可能?错误 sa...

    我正在尝试在图像数据集上训练 CNN 模型,但无法获得 TruePositives、TrueNegatives、FalsePositives 和 FalseNegatives 的十进制值。这怎么可能呢?

    ERROR sample
    Epoch 1/3
    36/36  69s 2s/step - false_negatives: 30.1351 - false_positives: 35.3784 - loss: 2.1995 - true_negatives: 389.0540 - true_positives: 437.6487
    
    

    有一些(tp+tn+fp+tn)不等于样本总数。

    完整代码

    
    import pandas as pd
    import tensorflow as tf
    from tensorflow.keras.preprocessing.image import ImageDataGenerator
    
    from tensorflow.keras.layers import Dense,Flatten,InputLayer,Conv2D,MaxPooling2D,Concatenate,Input,BatchNormalization
    from tensorflow.keras.models import Sequential,Model
    from tensorflow.keras.losses import BinaryCrossentropy,CategoricalCrossentropy
    from tensorflow.keras.optimizers import Adam
    import matplotlib.pyplot as plt
    from tensorflow.keras.models import Model
    from sklearn.metrics import classification_report
    from tensorflow.keras.callbacks import EarlyStopping
    
    datagen=ImageDataGenerator(rescale=1.0/255.0)
    train_gen=datagen.flow_from_directory('train',class_mode='binary',
                                          target_size=(224,224),batch_size=32,shuffle=True)
    
    
    Output:
    
    Found 1146 images belonging to 2 classes.
    
    tp = tf.keras.metrics.TruePositives()
    tn = tf.keras.metrics.TrueNegatives()
    fp = tf.keras.metrics.FalsePositives()
    fn = tf.keras.metrics.FalseNegatives()
    tp.update_state([0.4, .9, .7, .8], [1.0, 0.0, 1.0, 1.0])
    tp.result()
    
    output
    <tf.Tensor: shape=(), dtype=float32, numpy=3.0>
    
    model_input=Input(shape=(224,224,3))
    
    x=Conv2D(filters=32, kernel_size=(3,3),activation='relu',padding='valid')(model_input)
    x=MaxPooling2D(pool_size=(2,2),strides=2)(x)
    x=Conv2D(filters=64, kernel_size=(3,3),activation='relu',padding='valid')(x)
    x=MaxPooling2D(pool_size=(2,2),strides=2)(x)
    x=BatchNormalization()(x)
    x=Conv2D(filters=64, kernel_size=(3,3),activation='relu',padding='valid')(x)
    x=MaxPooling2D(pool_size=(2,2),strides=2)(x)
    x=BatchNormalization()(x)
    x=Flatten()(x)
    x=Dense(units=1000,activation='relu')(x)
    output=Dense(units=1,activation='sigmoid')(x)
    model=Model(inputs=model_input,outputs=output)
    
    model.compile(optimizer=Adam(),loss=BinaryCrossentropy(),metrics=[tp,fp,fn,tn])
    early_stopping = EarlyStopping(monitor='val_loss', patience=2,restore_best_weights=True)
    
    
    history=model.fit(x=train_gen,epochs=3,callbacks=[early_stopping])
    

    十进制值错误

    Epoch 1/3
    36/36  69s 2s/step - false_negatives: 30.1351 - false_positives: 35.3784 - loss: 2.1995 - true_negatives: 389.0540 - true_positives: 437.6487
    Epoch 2/3
    36/36  61s 2s/step - false_negatives: 7.8378 - false_positives: 13.5135 - loss: 0.1692 - true_negatives: 283.1081 - true_positives: 300.4054
    Epoch 3/3
    36/36  65s 2s/step - false_negatives: 2.3243 - false_positives: 3.0811 - loss: 0.0546 - true_negatives: 289.8108 - true_positives: 308.3513
    
    
  • 存在 Remove 方法(不确定提出这个问题时是否存在)

    例如:

    var raw = "your json text";
    var o = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(raw);
    o.Property("totalItems").Remove()
    return o.ToString();
    

    或您的确切输入

    var parent = JsonConvert.DeserializeObject<JObject>(raw);
    ((JArray)parent.Property("results").Value)
        .Select(jo => (JObject)jo)
        .ToList()
        .ForEach(x => 
            x
                .Properties()
                .ToList()
                .ForEach(p =>
                {
                    if (p.Name != "name")
                        p.Remove();
                }))
        //.Dump();
        ;
    
  • 当 TensorFlow 对批次进行平均并为您提供此指标的“聚合”版本时,可能会发生这种情况。要测试这一点,请尝试使用 1 个样本批次大小。

返回
作者最近主题: