如何更正以下错误代码:ValueError:无法为Tensor'InputData / X:0'提供形状值(64,15),其形状为'(?,16,1)'

时间:2017-11-15 04:24:05

标签: python tensorflow tflearn

我正在尝试使用LSTM神经网络来执行预测。数据集对每个Y值都有16 X值。据我所知,列车X&的形状存在问题。 Y阵列或测试X& Y阵列或两者。我试过重塑,看来我的调整不正确。下面是Jupyter Notebook输出的代码。提前感谢您的见解。

from __future__ import division, print_function, absolute_import

#import pandas as pd
import tflearn
import numpy as np
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf

def myRNN():
    tf.reset_default_graph()
    # Network building
    net = tflearn.input_data(shape=[None, 16, 1])
    net = tflearn.lstm(net, 32, dropout=0.8,bias=True)
    net = tflearn.fully_connected(net, 1, activation='relu')
    net = tflearn.regression(net, optimizer='adam', loss='mean_square', learning_rate=0.003)

    #Gather the Training Data
    csvData = np.genfromtxt('LabelCall5Data.csv', delimiter=',')
    trainX = csvData[0:3360,0:15]
    trainY = csvData[0:3360,16]

    #Transpose the input Data
    trainX = np.reshape(trainX, (-1, 16, 1))
    trainY = np.reshape(trainY, (-1, 1))
    print('trainX Shape: ', trainX.shape)
    print('trainY Shape: ', trainY.shape)

    #Gather the Testing Data
    testX = csvData[3361:,0:15]
    testY = csvData[3361:,16]
    print('testY Shape: ', testX.shape)
    print('testY Shape: ', testY.shape)

    # Training
    model = tflearn.DNN(net)
    model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)

    # Predict the future values
    predictY = model.predict(testX)

    print("---------TEST ERROR-----------")
    expected = np.array(testY).flatten()
    predicted = np.array(predictY).flatten()
    error = sum(((expected - predicted) **2)/len(expected))
    print(error)`enter code here`

输出低于。

Training Step: 49  | total loss: 24915.56836 | time: 0.557s
| Adam | epoch: 001 | loss: 24915.56836 - binary_acc: 0.0000 -- iter: 3136/3150

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-130-e193b95cc714> in <module>()
----> 1 myRNN()

<ipython-input-129-b039a187b4c6> in myRNN()
     37     # Training
     38     model = tflearn.DNN(net)
---> 39     model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)
     40 
     41     # Predict the future values

~/anaconda3/lib/python3.6/site-packages/tflearn/models/dnn.py in fit(self, X_inputs, Y_targets, n_epoch, validation_set, show_metric, batch_size, shuffle, snapshot_epoch, snapshot_step, excl_trainops, validation_batch_size, run_id, callbacks)
    214                          excl_trainops=excl_trainops,
    215                          run_id=run_id,
--> 216                          callbacks=callbacks)
    217 
    218     def fit_batch(self, X_inputs, Y_targets):

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in fit(self, feed_dicts, n_epoch, val_feed_dicts, show_metric, snapshot_step, snapshot_epoch, shuffle_all, dprep_dict, daug_dict, excl_trainops, run_id, callbacks)
    337                                                        (bool(self.best_checkpoint_path) | snapshot_epoch),
    338                                                        snapshot_step,
--> 339                                                        show_metric)
    340 
    341                             # Update training state

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in _train(self, training_step, snapshot_epoch, snapshot_step, show_metric)
    845             if show_metric and self.metric is not None:
    846                 eval_ops.append(self.metric)
--> 847             e = evaluate_flow(self.session, eval_ops, self.test_dflow)
    848             self.val_loss = e[0]
    849             if show_metric and self.metric is not None:

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in evaluate_flow(session, ops_to_evaluate, dataflow)
    996 
    997         while feed_batch:
--> 998             r = session.run(ops_to_evaluate, feed_batch)
    999             current_batch_size = get_current_batch_size(feed_batch, dataflow)
   1000             for i in range(len(r)):

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1094                 'Cannot feed value of shape %r for Tensor %r, '
   1095                 'which has shape %r'
-> 1096                 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
   1097           if not self.graph.is_feedable(subfeed_t):
   1098             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (64, 15) for Tensor 'InputData/X:0', which has shape '(?, 16, 1)'

1 个答案:

答案 0 :(得分:0)

问题在于,当您创建trainX时,您只需要15个值,而不是16个。

trainX = csvData[0:3360,0:15]仅为您提供第二维中的前15个频道。将其替换为trainX = csvData[0:3360,0:16]

并且您的测试数据具有相同的问题,在将其提供给网络之前不会reshape d。这导致没有正确数量的维度。