Keras输入层形状在输入层错误

ForNForN

我正在尝试通过构建来学习AI算法。我在这里找到有关Stackoverflow的问题我复制了此代码进行尝试,然后对其进行了修改。

import numpy as np
import tensorflow as tf
from tensorflow import keras as keras
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from tensorflow.python.keras import activations
# Importing the dataset
dataset = np.genfromtxt("data.txt", delimiter='')
X = dataset[:, :-1]
y = dataset[:, -1]

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.08, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)



# Initialising the ANN
#model = Sequential()

# Adding the input layer and the first hidden layer
#model.add(Dense(32, activation = 'relu', input_dim = 6))

# Adding the second hidden layer
#model.add(Dense(units = 32, activation = 'relu'))

# Adding the third hidden layer
#model.add(Dense(units = 32, activation = 'relu'))

# Adding the output layer

#model.add(Dense(units = 1))
#model = Sequential([
#    keras.Input(shape= (6),name= "digits"),
#    Dense(units = 32, activation = "relu"),
#    Dense(units = 32, activation = "relu"),
#    Dense(units = 1 , name = "predict")##

#])
#
input = keras.Input(shape= (6),name= "digits")
#x0 = Dense(units = 6)(input)
x1 = Dense(units = 32, activation = "relu")(input)
x2 = Dense(units = 32, activation = "relu")(x1)
output = Dense(units = 1 , name = "predict")(x2)

model = keras.Model(inputs = input , outputs= output)
#model.add(Dense(1))
# Compiling the ANN
#model.compile(optimizer = 'adam', loss = 'mean_squared_error')

# Fitting the ANN to the Training set
#model.fit(X_train, y_train, batch_size = 10, epochs = 200)

optimizer = keras.optimizers.Adam(learning_rate=1e-3)
loss = keras.losses.MeanSquaredError()

epochs = 200

for epoch in range(epochs):
    print("\nStart of epoch %d" % (epoch,))

    # Iterate over the batches of the dataset.
    for step in range(len(X_train)):

        # Open a GradientTape to record the operations run
        # during the forward pass, which enables auto-differentiation.
        with tf.GradientTape() as tape:

            # Run the forward pass of the layer.
            # The operations that the layer applies
            # to its inputs are going to be recorded
            # on the GradientTape.
            logits = model( X_train[step] , training=True)  # Logits for this minibatch

            # Compute the loss value for this minibatch.
            loss_value = loss(y_train[step], logits)

        # Use the gradient tape to automatically retrieve
        # the gradients of the trainable variables with respect to the loss.
        grads = tape.gradient(loss_value, model.trainable_weights)

        # Run one step of gradient descent by updating
        # the value of the variables to minimize the loss.
        optimizer.apply_gradients(zip(grads, model.trainable_weights))

        # Log every 200 batches.
        if step % 200 == 0:
            print(
                "Training loss (for one batch) at step %d: %.4f"
                % (step, float(loss_value))
            )
            print("Seen so far: %s samples" % ((step + 1) * 64))


y_pred = model.predict(X_test)

plt.plot(y_test, color = 'red', label = 'Real data')
plt.plot(y_pred, color = 'blue', label = 'Predicted data')
plt.title('Prediction')
plt.legend()
plt.show()

我修改了用于在处理时创建数据的代码。如果我使用model.fit,它将使用我提供的数据,但是我想在纪元开始从模拟中创建数据然后进行处理时。(对不起,英语不好,如果我不能很好地解释)

当我在第81行中启动代码时:

Exception has occurred: ValueError
Input 0 of layer dense is incompatible with the layer: : expected min_ndim=2, found ndim=1. Full shape received: (6,)

它给出一个异常。我尝试使用shape=(6,) shape=(6,1)或类似的方法,但无法解决任何问题。

莱斯库雷尔

调用keras模型时,您需要添加一个批处理维度:

logits = model( X_train[step][np.newaxis,:] , training=True)  # Logits for this minibatch

批次维度用于将多个样本馈送到网络。默认情况下,Keras假定输入具有批次尺寸。为了提供一个样品,Keras希望一批样品。在这种情况下,它表示形状为(1,6)。如果要批量喂入2个样品,则形状将为(2,6),依此类推。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

输入到 Keras 层

来自分类Dev

输入层的TensorFlow Keras尺寸错误

来自分类Dev

为什么 keras LSTM 层需要输入形状?

来自分类Dev

TensorFlow/Keras:输出层的形状错误

来自分类Dev

了解Keras层的形状

来自分类Dev

Keras/Tensorflow 输入到 RNN 层

来自分类Dev

Keras中LSTM层的输入维度

来自分类Dev

Keras自定义层每次都接收相同的输入形状

来自分类Dev

如何使用 lambda 层更改模型的输入形状

来自分类Dev

Caffe 嵌入层输入

来自分类Dev

Keras中Vanilla RNN的致密层的形状错误?

来自分类Dev

合并层的Keras错误

来自分类Dev

如何在tf.keras中使输入层显式

来自分类Dev

如何在keras的最后一层输入单个变量?

来自分类Dev

如何确定CNN Keras中密集层的输入大小?

来自分类Dev

Python Keras如何在将卷积层转换为lstm层后更改输入的大小

来自分类Dev

如何使Keras密集层处理3D张量作为此Softmax全连接层的输入?

来自分类Dev

层density_18的输入0与该层不兼容:输入形状的预期轴-1的值为3500,但接收到形状为[None,7]的输入

来自分类Dev

从前端输入时Keras形状错误

来自分类Dev

ANN绕过输入的隐藏层

来自分类Dev

小型MLP的Keras层形状不兼容

来自分类Dev

连接不同形状的keras层输出

来自分类Dev

Keras 层要求的形状与摘要中不同

来自分类Dev

Keras 形状错误 - 我正在输入它要求的形状

来自分类Dev

Keras 输入形状问题

来自分类Dev

当LSTM层的输入数量大于或小于该层中LSTM单元的数量时,Keras会做什么?

来自分类Dev

如何为 LSTM 输入合并两个不同形状的层?

来自分类Dev

输入图像大小如何影响全连接层的大小和形状?

来自分类Dev

输入到 1D Conv 层的数据集形状的困难

Related 相关文章

热门标签

归档