我有以下格式的输入和输出:
(X) = [[ 0 1 2]
[ 1 2 3]]
y = [ 3 4 ]是时间序列数据。任务是预测下一个数字。基本上,输入是由下面的代码片段构建的:
def split_sequence(arr,timesteps):
arr_len = len(arr)
X,y = [],[]
for i in range(arr_len):
end_idx = i + timesteps
if end_idx > arr_len-1:
break
input_component,output_component = arr[i:end_idx],arr[end_idx]
X.append(input_component)
y.append(output_component)
return np.array(X), np.array(y)现在,我想对输入的模型进行训练,并预测下一个数字。例如,x = [81,82,83]和预测的输出将是y = 84。我在角角上学会了怎么做。然而,我也想尝试在tensorflow中做到这一点。
下面是tensorflow中的代码:
# Data generator
def generate_batch(X,y,batch_size):
m = X.shape[0]
indexes = range(m)
n_batches = m // batch_size
for batch_index in np.array_split(indexes,n_batches):
yield X[batch_index],y[batch_index]
# parameters
n_inputs = 3
n_epochs = 1000
batch_size = 40
learning_rate = 0.01
n_steps = 3
# generate the input and output using split_sequence method
input, output = split_sequence(range(1000),n_steps)
# Define the input variables
X = tf.placeholder(tf.int32,shape=(None,n_inputs),name='X')
y = tf.placeholder(tf.float32,shape=(None),name='y')
theta = tf.Variable(tf.random_uniform([n_steps,1],-1.0,1.0),name='theta')
# predictions and error
y_predictions = tf.matmul(X,theta,name='predictions')
error = y_predictions - y
mse = tf.reduce_mean(tf.square(error),name='mse')
# train the model
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(mse)
init = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
for epoch in range(n_epochs):
for X_batch,y_batch in generate_batch(input,output,batch_size):
if epoch % 10 == 0:
print('epoch',epoch,'MSE=',mse.eval())
session.run(training_op,feed_dict={X:X_batch,y:y_batch})老实说,我完全被以下错误所困扰:
You must feed a value for placeholder tensor 'X' with dtype float and shape [?,3]。
我的输入是一个整数,这就是定义以下内容的原因:
X = tf.placeholder(tf.int32,shape=(None,n_inputs),name='X')有人能帮我解决这个问题吗?另外,如果我想增加偏差变量,我能实现上述输入吗?
发布于 2018-10-11 22:13:09
此错误是由以下一行引起的:
print('epoch',epoch,'MSE=',mse.eval())这是因为张量mse也依赖于占位符X和y。解决这一问题的一种方法是将培训循环更改为:
for X_batch,y_batch in generate_batch(input,output,batch_size):
mse_val, _ = session.run([mse, training_op],feed_dict={X:X_batch,y:y_batch})
if epoch % 10 == 0:
print('epoch',epoch,'MSE=',mse_val)此外,您还需要将X切换回tf.float32,因为tf.matmul与int和float不兼容。一旦输入数据,数据就会自动被抛出。
要添加一个偏差变量,您可以类似于定义theta。
b = tf.Variable(0.0, dtype=tf.float32, name='b')
...
y_predictions += bhttps://datascience.stackexchange.com/questions/39549
复制相似问题