我运行此代码,并收到以下错误。我该如何解决?

时间:2020-03-11 07:49:37

标签: python-3.x tensorflow placeholder

这是使用TensorFlow和ReLu激活功能预测股票价格走势的代码。我运行以下代码:

import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import pandas_datareader as web

dataset = web.DataReader('AAPL', data_source = 'yahoo', start = '1989-01-01', end = '2019-12-25')

import math

close_price = dataset.filter(['Close']).values
data_train_len = math.ceil(len(close_price) * .8)

sc = MinMaxScaler(feature_range = (0, 1))
sc_data = sc.fit_transform(close_price)

data_train = sc_data[0 : data_train_len, : ]
xtrain = []
ytrain = []
for i in range(60, len(data_train)):
    xtrain.append(data_train[i - 60 : i, 0])
    ytrain.append(data_train[i, 0])

xtrain, ytrain = np.array(xtrain), np.array(ytrain)
xtrain = np.reshape(xtrain, (xtrain.shape[0], xtrain.shape[1], 1))
print(xtrain.shape, ytrain.shape)

data_test = sc_data[data_train_len - 60 : , :]
xtest = []
ytest = close_price[data_train_len :, :]
for i in range(60, len(data_test)):
    xtest.append(data_test[i - 60 : i, 0])

xtest = np.array(xtest)
xtest = np.reshape(xtest, (xtest.shape[0], xtest.shape[1], 1))
print(xtest.shape, ytest.shape)

# Number of stock in training data
n_stocks = xtrain.shape[1]

#Model architecture parameters
n_neurons_1 = 1024
n_neurons_2 = 512
n_neurons_3 = 256
n_neurons_4 = 128

# Session
sesh = tf.InteractiveSession()

# Define two variables as placeholders
a = tf.placeholder(dtype = tf.float32, shape = [None, n_stocks])
b = tf.placeholder(dtype = tf.float32, shape = [1, None])

# Initializers
sig = 1
weight_init = tf.variance_scaling_initializer(mode = "fan_avg", distribution = "uniform", scale = 
sig)
bias_init = tf.zeros_initializer()

# Hidden weights
w_hid_1 = tf.Variable(weight_init([n_stocks, n_neurons_1]))
bias_hid_1 = tf.Variable(bias_init([n_neurons_1]))

w_hid_2 = tf.Variable(weight_init([n_neurons_1, n_neurons_2]))
bias_hid_2 = tf.Variable(bias_init([n_neurons_2]))

w_hid_3 = tf.Variable(weight_init([n_neurons_2, n_neurons_3]))
bias_hid_3 = tf.Variable(bias_init([n_neurons_3]))

w_hid_4 = tf.Variable(weight_init([n_neurons_3, n_neurons_4]))
bias_hid_4 = tf.Variable(bias_init([n_neurons_4]))

# Output weights
w_out = tf.Variable(weight_init([n_neurons_4, 1]))
bias_out = tf.Variable(bias_init([1]))

# Hidden layers
hid_1 = tf.nn.relu(tf.add(tf.matmul(a, w_hid_1), bias_hid_1))
hid_2 = tf.nn.relu(tf.add(tf.matmul(hid_1, w_hid_2), bias_hid_2))
hid_3 = tf.nn.relu(tf.add(tf.matmul(hid_2, w_hid_3), bias_hid_3))
hid_4 = tf.nn.relu(tf.add(tf.matmul(hid_3, w_hid_4), bias_hid_4))

# Transposed Output layer
out = tf.transpose(tf.add(tf.matmul(hid_4, w_out), bias_out))

# Cost function
mse = tf.reduce_mean(tf.squared_difference(out, b))
rmse = tf.sqrt(tf.reduce_mean(tf.squared_difference(out, b)))

opt1 = tf.train.AdamOptimizer().minimize(mse)
opt2 = tf.train.AdamOptimizer().minimize(rmse)

sesh.run(tf.global_variables_initializer())

# Setup plot
plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(111)
line1, = ax1.plot(ytest)
line2, = ax1.plot(ytest * 0.5)
plt.show()

# Fitting neural network
batch_size = 256
mse_train = []
rmse_train = []
mse_test = []
rmse_test = []

# Run tensorflow
epochs = 10
for epoch in range(epochs):

  # Training data is shuffled
  shuffle_ind = np.random.permutation(np.arange(len(ytrain)))
  xtrain = xtrain[shuffle_ind]
  ytrain = ytrain[shuffle_ind]

  # Minibatch training
  for i in range(0, len(ytrain) // batch_size):
    start = i * batch_size
    batch_x = xtrain[start : start + batch_size]
    batch_y = ytrain[start : start + batch_size]
    # Run optimizer with batch
    sesh.run(opt1, feed_dict = {a : batch_x, b : batch_y})
    sesh.run(opt2, feed_dict = {a : batch_x, b : batch_y})

我收到以下错误: ValueError:无法为张量为'(?,60)'的张量'Placeholder_30:0'输入形状(256,60,1)的值

“使用批处理运行优化器”下的最后两行均出现此错误。我该如何解决?

1 个答案:

答案 0 :(得分:0)

似乎您要输入不适合占位符的数据(我认为您是占位符a),这是将占位符更改为a = tf.placeholder(dtype = tf.float32, shape = [None, n_stocks, 1])或更改xtest和xtrain尺寸的简单方法(该行使用重塑形状),方法是使用np.squeeze()缩小最后一个尺寸。