张量流中的简单神经网络->形状问题

时间:2020-08-25 11:56:32

标签: python tensorflow neural-network

我有两个数据列表(x1,y1),(x2,y2)...

我不知道x和y之间的方程。因此,我尝试使用神经网络来找到它。

hyperbolic.txt文件具有(x1,y1),(x2,y2)...

代码在下面,但不起作用。

ValueError: Cannot feed value of shape (30,) for Tensor 'Placeholder:0', which has shape '(?, 1)'

我猜np_poses_x,np_poses_y的形状可能是错误的,但是我无法提出如何更改它的方法。

  • 我认为它们都应该具有(30,1)的形状。

import tensorflow as tf
import numpy as np
from tqdm import tqdm
import random

class datasource(object):
    def __init__(self, xx, yy):
        self.x = xx
        self.y = yy

def get_data(directory, dataset):
    xx = []
    yy = []

    with open(directory+dataset) as f:
        for line in f:
            p0,p1 = line.split()
            p0 = float(p0)
            p1 = float(p1)
            xx.append((p0))
            yy.append((p1))

    return datasource(xx, yy)


def gen_data(source):
    while True:
        indices = list(range(len(source.x)))
        random.shuffle(indices)
        for i in indices:
            yval = source.x[i]
            xval = source.y[i]
            yield xval, yval

def gen_data_batch(source, batch_size):
    data_gen = gen_data(source)
    while True:
        x_batch = []
        y_batch = []

        for _ in range(batch_size):
            _x, _y = next(data_gen)
            x_batch.append(_x)
            y_batch.append(_y)

        yield np.array(x_batch), np.array(y_batch)

X1 = tf.placeholder(tf.float32, shape=[None, 1])
Y = tf.placeholder(tf.float32, shape=[None, 1])

W1 = tf.Variable(tf.random_normal([1, 50], stddev=0.01))
L1 = tf.nn.relu(tf.matmul(X1, W1))

W2 = tf.Variable(tf.random_normal([50, 256], stddev=0.01))
L2 = tf.nn.relu(tf.matmul(L1, W2))

W3 = tf.Variable(tf.random_normal([256, 1], stddev=0.01))
model = tf.matmul(L2, W3)

cost = tf.reduce_mean(tf.square(model-Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

datasource = get_data('', 'hyperbolic.txt')

max_iterations = 100000
batch = 30
data_gen = gen_data_batch(datasource, batch)
for i in range(max_iterations):
    np_poses_x, np_poses_y = next(data_gen)
    feed = {X1: np_poses_x, model: np_poses_y}
    sess.run(optimizer, feed_dict=feed)
    np_loss = sess.run(cost, feed_dict=feed)

1 个答案:

答案 0 :(得分:1)

您做对了,您需要为网络提供(N,1)张量,而不是(N,)张量。

最简单的解决方案可能是使用np.newaxis(即None)或np.reshape函数在numpy端添加新维度。

因此您可以在gen_data_batch中应用它,例如将yield np.array(x_batch), np.array(y_batch)替换为yield np.array(x_batch)[:, np.newaxis], np.array(y_batch)[:, np.newaxis]

您还可以在np_poses_xnp_poses_y上添加此新轴:

feed = {X1: np_poses_x.reshape((len(np_poses_x), 1)),
        model: np_poses_y.reshape((len(np_poses_y), 1))}