You need to enable JavaScript to run this app. 求助:解决‘仅尺寸为1的数组可转换为Python标量’报错问题
优惠活动
大模型
产品
解决方案
定价
更多

求助:解决‘仅尺寸为1的数组可转换为Python标量’报错问题

Fixing "Only size-1 arrays can be converted to Python scalars" in TensorFlow GAN Code

Let's break down the issues causing this error and walk through how to fix them step by step:

1. Missing tf.reduce_mean in Discriminator Loss

The root cause of your scalar conversion error is in how you calculate the discriminator loss:

cost_disc=-tf.reduce_mean(tf.log(disc_real_out))+tf.log(1. -disc_fake_out)

You added tf.reduce_mean to the first term to collapse it into a scalar, but left the second term as a batch-sized tensor. When you run this in the session, dl will be a numpy array of size 128 (your batch size) instead of a single float. Python throws the error because %f expects a scalar value, not an array.

Fix: Wrap the second term in tf.reduce_mean too:

cost_disc = -tf.reduce_mean(tf.log(disc_real_out)) + tf.reduce_mean(tf.log(1. - disc_fake_out))

2. Typo in Optimizer Variable Names

You defined your optimizers as optin_gen and optin_disc, but later tried to use optim_gen (a misspelled variable) to set up training operations:

training_gen=optim_gen.minimize(cost_gen,var_list=vars_gen)
training_disc=optim_gen.minimize(cost_disc,var_list=vars_disc)

This will trigger a NameError once you fix the loss issue. Fix: Correct the variable names to match your definitions:

training_gen = optin_gen.minimize(cost_gen, var_list=vars_gen)
training_disc = optin_disc.minimize(cost_disc, var_list=vars_disc)

3. Session Scope Issue for Image Generation

After your with tf.Session() as sess: block finishes, the session closes automatically. But you try to run sess.run(gen_out) later when generating the canvas—this will fail because the session is no longer active.

Fix: Move all code that uses the session inside the block:

with tf.Session() as sess:
    sess.run(init)
    for step in range(1, num_steps+1):
        batch_x, _ = df.train.next_batch(batch_size)
        noise_temp = np.random.uniform(-1., 1., size=[batch_size, noise_dim])
        feed_dict = {disc_inp: batch_x, gen_inp: noise_temp}
        _, _, gl, dl = sess.run([training_gen, training_disc, cost_gen, cost_disc], feed_dict=feed_dict)
        if step % 2000 == 0 or step == 1:
            print('Step %i: Generator Loss: %f, Discriminator Loss: %f' % (step, gl, dl))
    print("finished!")
    # Move image generation logic inside the active session
    n = 6
    canvas = np.empty((28 * n, 28 * n))
    for i in range(n):
        z= np.random.uniform(-1., 1., size=[n, noise_dim])
        g= sess.run(gen_out, feed_dict={gen_inp: z})
        g= -1 * (g - 1)
        for j in range (n):
            canvas[i * 28:(i + 1) * 28, j * 28:(j +1) * 28] = g[j].reshape([28, 28])
    plt.figure(figsize=(n, n))
    plt.imshow(canvas, origin="upper", cmap="gray")
    plt.show()

Debugging Tip: Check Tensor Shapes

If you're ever unsure about tensor dimensions, add shape checks during development:

print("cost_gen shape:", cost_gen.get_shape())
print("cost_disc shape:", cost_disc.get_shape())

Both should output () (indicating a scalar) if your loss calculations are correct.

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:55:01