Tensorflow批次大小和实际输出之间的形状不兼容

2024-10-08 20:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试创建一个简单的网络应用程序,用于交互式神经网络实验。我对Tensorflow和机器学习还很陌生,所以我想从标准普尔500指数的一个简单的时间序列回归开始。在

我遇到的问题是以下错误:

InvalidArgumentError (see above for traceback): Incompatible shapes: [32,1] vs. [1248,1]

在批处理大小为32而实际数据大小为1248的情况下。当会话运行时,它由以下代码行产生:

tMSE = tf.reduce_mean(tf.square(y_hat - train_y))

这是源代码

def retrieve_data():
"""Retrieves the data - to be expanded for custom database access + S3 retrieval + URL"""
result = pd.read_csv('snp_data.csv', parse_dates=['Date'], index_col=['Date'])
return result

def get_features(data, columns):
    features = data.ix[:, columns]
    return features

def preprocess(data):
    """Data preprocessing"""
    result = (data - data.mean()) / data.std(ddof=0)
    result = result.fillna(0)
    return result

def init_weights(shape):
    """ Weights initialization """
    weights = tf.random_normal(shape=shape, stddev=0.1)
    return tf.Variable(weights)

def forwardprop(X, w_1, w_2):
    """Forward propagation"""
    h = tf.nn.relu(tf.matmul(X, w_1))
    y_hat = tf.matmul(h, w_2)
    return y_hat

@app.route('/train')
def train():
    data = retrieve_data()

    train_x = get_features(data, columns=['Open', 'Close'])
    train_x = preprocess(data=train_x).as_matrix().astype(np.float32)
    train_x = train_x[:(len(train_x) - (len(train_x) % 32))]

    train_y = get_features(data, columns=['Adj Close']).as_matrix().astype(np.float32)
    train_y = train_y[:(len(train_y) - (len(train_y) % 32))]

    # Number of input nodes
    n_features = train_x.shape[1]

    # Number of output nodes
    output_nodes = train_y.shape[1]

    # Number of hidden nodes
    hidden_nodes = 20

    # TF Placeholders for the inputs and outputs
    tx = tf.placeholder(tf.float32, shape=(None, n_features))
    ty = tf.placeholder(tf.float32, shape=(None, output_nodes))

    # Weight initializations
    tW1 = init_weights(shape=(n_features, hidden_nodes))
    tW2 = init_weights(shape=(hidden_nodes, output_nodes))

    # Forward propagation
    y_hat = forwardprop(tx, tW1, tW2)

    # Backward Propagation
    tMSE = tf.reduce_mean(tf.square(y_hat - train_y))
    learning_rate = 0.025
    tOptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    tOptimize = tOptimizer.minimize(tMSE)

    batch_size = 32
    n_epochs = 8

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for i_e in range(n_epochs):
            for i in range(0, train_x.shape[0], batch_size):
                batch_X = train_x[i:i + batch_size, ...]
                batch_y = train_y[i:i + batch_size]

                _, loss = sess.run([tOptimize, tMSE], feed_dict={tx: batch_X, ty: batch_y})
                print(i, loss)
    return 'Flask Dockerized'

下面是记录的错误:

^{pr2}$

Tags: fordatareturninittfhatdefbatch
1条回答
网友
1楼 · 发布于 2024-10-08 20:19:55

您应该更改您的tMSE代码:

# original wrong code: tMSE = tf.reduce_mean(tf.square(y_hat - train_y))
tMSE = tf.reduce_mean(tf.square(y_hat - ty))

相关问题 更多 >

    热门问题