python - 这个错误意味着什么 : `y` argument is not supported when using python generator as input

标签 python tensorflow keras deep-learning lstm

我尝试开发一个网络,并使用 python 生成器作为数据提供者。一切看起来都不错,直到模型开始适合,然后我收到此错误:

ValueError: `y` argument is not supported when using dataset as input.
我校对了每一行,我认为问题出在 x_test 的格式上。和 y_test馈入网络。经过数小时的谷歌搜索,并多次更改格式,错误仍然存​​在。
你能帮我修一下吗?您可以在下面找到完整的代码:
import os
import numpy as np
import pandas as pd
import re  # To match regular expression for extracting labels

import tensorflow as tf

print(tf.__version__)


def xfiles(filename):
    if re.match('^\w{12}_x\.csv$', filename) is None:
        return False
    else:
        return True


def data_generator():
    folder = "i:/Stockpred/csvdbase/datasets/DS0002"
    file_list = os.listdir(folder)
    x_files = list(filter(xfiles, file_list))
    x_files.sort()
    np.random.seed(1729)
    np.random.shuffle(x_files)

    for file in x_files:
        filespec = folder + '/' + file
        xs = pd.read_csv(filespec, header=None)

        yfile = file.replace('_x', '_y')
        yfilespec = folder + '/' + yfile
        ys = pd.read_csv(open(yfilespec, 'r'), header=None, usecols=[1])

        xs = np.asarray(xs, dtype=np.float32)
        ys = np.asarray(ys, dtype=np.float32)

        for i in range(xs.shape[0]):
            yield xs[i][1:169], ys[i][0]


dataset = tf.data.Dataset.from_generator(
    data_generator,
    (tf.float32, tf.float32),
    (tf.TensorShape([168, ]), tf.TensorShape([])))
dataset = dataset.shuffle(buffer_size=16000, seed=1729)
# dataset = dataset.batch(4000, drop_remainder=True)
dataset = dataset.cache('R:/Temp/model')


def is_test(i, d):
    return i % 4 == 0


def is_train(i, d):
    return not is_test(i, d)


recover = lambda i, d: d

test_dataset = dataset.enumerate().filter(is_test).map(recover)
train_dataset = dataset.enumerate().filter(is_train).map(recover)

x_test = test_dataset.map(lambda x, y: x)
y_test = test_dataset.map(lambda x, y: y)

x_train = train_dataset.map(lambda x, y: x)
y_train = train_dataset.map(lambda x, y: y)

print(x_train.element_spec)
print(y_train.element_spec)
print(x_test.element_spec)
print(y_test.element_spec)

# define an object (initializing RNN)
model = tf.keras.models.Sequential()

# first LSTM layer
model.add(tf.keras.layers.LSTM(units=168, activation='relu', return_sequences=True, input_shape=(168, 1)))
# dropout layer
model.add(tf.keras.layers.Dropout(0.2))

# second LSTM layer
model.add(tf.keras.layers.LSTM(units=168, activation='relu', return_sequences=True))
# dropout layer
model.add(tf.keras.layers.Dropout(0.2))

# third LSTM layer
model.add(tf.keras.layers.LSTM(units=80, activation='relu', return_sequences=True))
# dropout layer
model.add(tf.keras.layers.Dropout(0.2))

# fourth LSTM layer
model.add(tf.keras.layers.LSTM(units=120, activation='relu'))
# dropout layer
model.add(tf.keras.layers.Dropout(0.2))

# output layer
model.add(tf.keras.layers.Dense(units=1))

model.summary()

# compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

model.fit(x_train.as_numpy_iterator(), y_train.as_numpy_iterator(), batch_size=32, epochs=100)

predicted_stock_price = model.predict(x_test)
一切看起来都很好,直到模型开始适合。我收到这个错误:
ValueError: `y` argument is not supported when using dataset as input.
你能帮忙解决吗?

最佳答案

docs说:

y - Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, generator, or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from x).


所以,我想你应该有一个生成器来提供样本和标签的元组。

关于python - 这个错误意味着什么 : `y` argument is not supported when using python generator as input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62609988/

相关文章:

python - CuDNNLSTM(而不是 LSTM)层的意外结果

python - Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 层数

Python编码utf错误

python - 使用 Selenium Python 从网页中提取 SVG

python - 启用急切执行时如何运行并行map_fn

tensorflow - 微调 Blenderbot

python - “张量”对象没有属性 '_keras_history'

python - Pandas .loc[] 副作用将 bools 更改为 floats

python - 从 psycopg2 connection.commit() 获取受影响的行数

python-2.7 - 使用Tensorflow进行RNN回归?