簡體   English   中英

張量流中的簡單神經網絡 -> 形狀問題

[英]Simple neural network in tensorflow -> shape problem

我有兩個數據列表 (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)

你做對了,你需要為你的網絡提供一個(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))}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM