【问题标题】:I run this code and I get the following error. How do I fix this?我运行此代码并收到以下错误。我该如何解决?
【发布时间】:2020-06-23 03:50:47
【问题描述】:

这是使用 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) 的值

“Run Optimizer with Batch”下的最后两行都会出现此错误。我该如何解决这个问题?

【问题讨论】:

  • 你做了什么来尝试自己解决这个问题?

标签: python-3.x tensorflow placeholder


【解决方案1】:

您似乎试图提供不适合占位符的数据(我认为您是占位符 a),将占位符更改为 a = tf.placeholder(dtype = tf.float32, shape = [None, n_stocks, 1]) 或更改您的 xtest 和 xtrain 维度的简单方法(您使用 reshape) 通过使用 np.squeeze() 减少最后一个维度。

【讨论】:

  • 非常感谢您的帮助。不幸的是,我试过了,但没有奏效。
  • 实际上,我的意思是你试图将一个维度为 (256, 60, 1) 的 numpy 数组作为 feed_dict 放到维度 (Any, 60) 的占位符中。这个问题可以通过将您的输入重塑为 (256,60) 来解决,使其适合您的占位符或更改您的占位符形状。您可以在使用 sess.run 之前检查您的尺寸。
猜你喜欢
  • 2023-01-07
  • 2021-06-29
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2012-08-31
  • 2020-01-22
相关资源
最近更新 更多