gpt4 book ai didi

python - 如何在Python中修复 "TypeError: The added layer must be an instance of class Layer."

转载 作者:行者123 更新时间:2023-12-01 01:05:25 25 4
gpt4 key购买 nike

我已经写了一个类似于 helloworld 的神经网络。问题是我经常收到这样的错误:

"Traceback (most recent call last):
File "C:/Users/Pigeonnn/PycharmProjects/Noss/Network.py", line 21, in <module>
model.add(keras.layers.InputLayer(input_shape))
File "C:\Users\Pigeonnn\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 442, in _method_wrapper
method(self, *args, **kwargs)
File "C:\Users\Pigeonnn\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 145, in add
'Found: ' + str(layer))
TypeError: The added layer must be an instance of class Layer. Found: <keras.engine.input_layer.InputLayer object at 0x0000015EDB394DA0>"

这是我的代码:

import keras
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.utils import shuffle
import tensorflow as tf

seed = 10
np.random.seed(seed)

dataset = np.loadtxt("dataset2.csv",delimiter=',',skiprows=1)
dataset = shuffle(dataset)

X = dataset[:,2:]
Y = dataset[:,1]

(X_train,X_test,Y_train,Y_test) = train_test_split(X, Y, test_size=0.15, random_state=seed)
input_shape = (13,)

model = tf.keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape))
model.add(keras.layers.core.Dense(128, activation='relu'))
model.add(keras.layers.core.Dense(128, activation='relu'))
model.add(keras.layers.core.Dense(4, activation='sigmoid'))

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

model.fit(X_train,Y_train,epochs=20)

编辑:经过一些调整(更改损失函数,删除 tf 模型),我遇到了另一个错误,这次是:

Traceback (most recent call last):  File "C:/Users/Pigeonnn/PycharmProjects/Noss/Network.py", line 28, in     model.fit(X_train,Y_train,epochs=20)  File "C:\Users\Pigeonnn\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training.py", line 952, in fit    batch_size=batch_size)  File "C:\Users\Pigeonnn\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training.py", line 789, in _standardize_user_data    exception_prefix='target')  File "C:\Users\Pigeonnn\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training_utils.py", line 138, in standardize_input_data    str(data_shape))ValueError: Error when checking target: expected dense_3 to have shape (4,) but got array with shape (1,)

最佳答案

您同时使用 tf.keraskeras 模块,它们兼容。仅使用一种并保持一致。

关于python - 如何在Python中修复 "TypeError: The added layer must be an instance of class Layer.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55407970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com