python - 占位符的尺寸如何用于 tensorflow ?

标签 python tensorflow keras neural-network

所以假设我有x_trainy_train,它们是数组,并且该数组的每个元素都是一个数据点(以数组形式)(所以x_train 的形式为 x_train[i][j])。所以 x_train[0] 代表训练集中的第一个数据点(以数组形式),假设我想创建一个简单的回归

所以我编码了这个

input = tf.placeholder(tf.float32, shape=[len(data[0]),None])
target = tf.placeholder(tf.flaot32, shape=[len(data[0]),None])

network = tf.layers.Dense(10, tf.keras.activations.relu)(input)
network = tf.layers.BatchNormalization()(network)

network = tf.layers.Dense(10,tf.keras.activations.relu)(network)
network = tf.layers.BatchNormalization()(network)

network = tf.layers.Dense(10,tf.keras.activations.linear)(network)

cost = tf.reduce_mean((target - network)**2)

optimizer = tf.train.AdamOptimizer().minimize(cost)

with tf.Session() as sess:
     for epoch in range(1000):
           _, val = sess.run([optimizer,cost], feed_dict={input: x_train, target: y_train})
           print(val)

但是这是正确的吗?我不确定占位符的尺寸是否匹配。当我尝试运行这段代码时, 我收到错误消息

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

所以我尝试的是交换占位符的尺寸大小的位置,所以 更改的占位符是

    input = tf.placeholder(tf.float32, shape=[None,len(data[0])])
    target = tf.placeholder(tf.float32, shape=[None,len(data[0])]) 

但是有了这些,我就会收到错误消息

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value dense/bias
 [[{{node dense/bias/read}}]]

最佳答案

我能够通过在 axis=0 处的 x_trainy_train 上执行 np.expand_dims() 来解决上述问题 并在优化模型之前使用 sess.run(tf.global_variable_initializer()) 初始化batch_norm 和网络参数。

注意:占位符形状的第一个维度中存在 None 是可以的,因为它允许 TensorFlow 在批量大小未知时训练模型(即使占位符形状的其他维度也是如此) )。该错误是由于输入和占位符尺寸不匹配造成的。您的输入(x_trainy_train)可能是一维张量,而占位符要么需要二维张量,要么需要将一维向量 reshape 为二维。

请找到我的以下相同实现以及验证实现的 matplotlib 图:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

data = [[1,2,3,4,5,6,7,8,9,10],
        [11,12,13,14,15,16,17,18,19,20]]
x_train = data[0]
y_train = data[1]
x_train = np.expand_dims(x_train, 0)
y_train = np.expand_dims(y_train, 0)

input = tf.placeholder(tf.float32, shape=[None, len(data[0])])
target = tf.placeholder(tf.float32, shape=[None, len(data[1])])

network = tf.layers.Dense(10, tf.keras.activations.relu)(input)
network = tf.layers.BatchNormalization()(network)

network = tf.layers.Dense(10,tf.keras.activations.relu)(network)
network = tf.layers.BatchNormalization()(network)

network = tf.layers.Dense(10,tf.keras.activations.linear)(network)

cost = tf.reduce_mean((target - network)**2)

optimizer = tf.train.AdamOptimizer().minimize(cost)

costs = []

with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())
     for epoch in range(1000):
        _, val = sess.run([optimizer,cost], feed_dict={input: x_train, target: y_train})
        costs.append(val)
        print(val)


fig, ax = plt.subplots(figsize=(11, 8))
ax.plot(range(1000), costs)
ax.set_title("Costs vs epochs")
ax.set_xlabel("Epoch")
ax.set_ylabel("Avg. val. accuracy")

这是成本与时期的关系图:

成本与纪元 enter image description here

此外,要使用新数据测试网络(例如)x_test = [[21,22,23,24,25,26,27,28,29,30]],您可以使用下面的代码:

 y_pred = sess.run(network,feed_dict={input: x_test})

PS:确保您使用上面创建的相同 Tensorflow Session sess 来运行推理(除非您不保存和加载模型检查点)

关于python - 占位符的尺寸如何用于 tensorflow ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59559297/

相关文章:

gpu - 有没有办法强制 Bazel 串行运行测试

python - Tensorflow 密集标签形状

python - Keras模型: Input shape dimension error for RL agent

python - 使用 keras fit_generator 时,如何让 Bokeh 更新显示某些度量与纪元的绘图?

python - 如何使用 wsgiref CGIHandler 摆脱运行 Flask 应用程序的额外 cgi-bin url 组件?

python - 检查数字是否步进的函数返回 false

python - NoneType 对象没有要获取的属性(Tkinter)

python - For 循环错误?

c++ - 如何从 C++ 中的原始指针数据构造一个 tensorflow::Tensor

python - CNN 使用具有显着尺寸差异的图像