ValueError: 无法为形状为(6165, 5)的值馈送到张量’Placeholder_1:0’,其形状为'(?, 1)’

> 警告:TensorFlow contrib模块将不会包含在TensorFlow 2.0中。更多信息请见:
 * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
 * https://github.com/tensorflow/addons
如果您依赖于那里未列出的功能,请提交问题。
警告:tensorflow:从C:/Users/SONSANGWOO/Desktop/Euroaquae/The_third_semester_at_BCN/ANN/Exercise/TimeSeriespy_RNN.py:74: BasicLSTMCell.__init__ (来自tensorflow.python.ops.rnn_cell_impl)已被弃用,将在未来版本中移除。更新说明:此类相当于tf.keras.layers.LSTMCell,并将在TensorFlow 2.0中被替换。
警告:tensorflow:从C:/Users/SONSANGWOO/Desktop/Euroaquae/The_third_semester_at_BCN/ANN/Exercise/TimeSeriespy_RNN.py:75: dynamic_rnn (来自tensorflow.python.ops.rnn)已被弃用,将在未来版本中移除。更新说明:请使用`keras.layers.RNN(cell)`,它等同于这个API
警告:tensorflow:从C:\Users\SONSANGWOO\Anaconda3\lib\site-packages\tensorflow\python\ops\tensor_array_ops.py:162: colocate_with (来自tensorflow.python.framework.ops)已被弃用,将在未来版本中移除。更新说明:位置由placer自动处理。
Traceback (most recent call last):
  File "<ipython-input-1-7716630f4e29>", line 1, in <module>
    runfile('C:/Users/SONSANGWOO/Desktop/Euroaquae/The_third_semester_at_BCN/ANN/Exercise/TimeSeriespy_RNN.py', wdir='C:/Users/SONSANGWOO/Desktop/Euroaquae/The_third_semester_at_BCN/ANN/Exercise')
  File "C:\Users\SONSANGWOO\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)
  File "C:\Users\SONSANGWOO\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/SONSANGWOO/Desktop/Euroaquae/The_third_semester_at_BCN/ANN/Exercise/TimeSeriespy_RNN.py", line 97, in <module>
    X: trainX, Y: trainY})
  File "C:\Users\SONSANGWOO\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 929, in run
    run_metadata_ptr)
  File "C:\Users\SONSANGWOO\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1128, in _run
    str(subfeed_t.get_shape())))
ValueError: 无法为形状为(6165, 5)的值馈送到张量'Placeholder_1:0',其形状为'(?, 1)'

我遇到了一个错误,我已经检查了每个变量的维度,看起来没有问题… 您能告诉我哪里出了问题以及如何修复吗?

我想做的-weather prediction。我的输入形状将是( xxxx , 5),这里 xxxx 是输入数据的行数,5 是输入的类型,包括平均温度等。

输出形状必须是(yyyy, 1),因为它的列将包含预测的降水量。

奇怪的是,当程序读取文件时,Data_Y 的形状是( hhhh, 5),本应是(yyyy, 1)。

我认为这是导致所有错误的原因。

输入文件的链接如下

输入文件

输入图片描述

我该如何解决这个问题?请伸出援手。

导入tensorflow as tf导入pandas as pd导入numpy as np导入matplotlib从matplotlib导入pyplot as plt
tf.reset_default_graph()
tf.set_random_seed(777)  # 可重复性
def MinMaxScaler(data):
    numerator = data - np.min(data, 0)
    denominator = np.max(data, 0) - np.min(data, 0)
    # 噪声项防止零除
    return numerator / (denominator + 1e-7)
# 训练参数
seq_length = 6
data_dim = 5
hidden_dim = 10
output_dim = 1
learning_rate = 0.01
iterations = 500
# Open, High, Low, Volume, Close
#df = pd.read_csv("precipitation_post.csv", quotechar='"', decimal=".")
#df = df.interpolate(method ='linear', limit_direction ='forward')
#xy = df.reindex(index=df.index[::-1])
xy = np.loadtxt('df.txt', dtype='double', delimiter=' ', skiprows=1)
#xy = xy[::-1]  # 训练/测试分割
train_size = int(len(xy) * 0.7)
train_set = xy[0:train_size]
test_set = xy[train_size - seq_length:] # 从[train_size - seq_length]索引开始使用过去的序列
# 缩放每个
train_set = MinMaxScaler(train_set)
test_set = MinMaxScaler(test_set)
x = xy
y = xy[:, [-1]] # 关闭作为标签
# 构建数据集
def build_dataset(time_series, seq_length):
    dataX = []
    dataY = []
    for i in range(0, len(time_series) - seq_length):
        _x = time_series[i:i + seq_length]
        _y = time_series[i + seq_length]
        print(_x, "->", _y)
        dataX.append(_x)
        dataY.append(_y)
    return np.array(dataX), np.array(dataY)
trainX, trainY = build_dataset(train_set, seq_length)
testX, testY = build_dataset(test_set, seq_length)
# 输入占位符
X = tf.placeholder(tf.float32, shape=[None, seq_length, data_dim])
Y = tf.placeholder(tf.float32, shape=[None, 1])
# 构建LSTM网络
cell = tf.contrib.rnn.BasicLSTMCell(
    num_units=hidden_dim, state_is_tuple=True, activation=tf.tanh)
outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
Y_pred = tf.contrib.layers.fully_connected(
    outputs[:, -1], output_dim, activation_fn=None)  # 我们使用最后一个单元的输出
# 成本/损失
loss = tf.reduce_sum(tf.square(Y_pred - Y))  # 平方和
# 优化器
optimizer = tf.train.AdamOptimizer(learning_rate)
train = optimizer.minimize(loss)
# RMSE
targets = tf.placeholder(tf.float32, [None, 1])
predictions = tf.placeholder(tf.float32, [None, 1])
rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    # 训练步骤
    for i in range(iterations):
        _, step_loss = sess.run([train, loss], feed_dict={
                                X: trainX, Y: trainY})
        print("[步骤: {}] 损失: {}".format(i, step_loss))
    # 测试步骤
    test_predict = sess.run(Y_pred, feed_dict={X: testX})
    rmse_val = sess.run(rmse, feed_dict={
                    targets: testY, predictions: test_predict})
    print("RMSE: {}".format(rmse_val))
    # 绘制预测
plt.plot(testY)
plt.plot(test_predict)
plt.xlabel("时间段")
plt.ylabel("降水量")
plt.show()

回答:

根据您提供的信息,以下是一个解决方案。显然,正如您可能已经意识到的那样,问题出在build_dataset函数中。您需要将您的函数更改为以下内容。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注