含3个特征的线性回归TensorFlow代码运行报ValueError错误求助
Fixing the
ValueError: setting an array element with a sequence in Your Linear Regression Code Hey Vijay, let's break down what's causing that error and get your model working properly step by step.
Core Error Cause
The immediate problem is with your INPUT_XOR dataset: every sample except the last one has 4 elements (like [1,72,50,33.6]), but the final entry is [96,54,0] which only has 3. This makes your input list an irregular sequence, and TensorFlow can't convert it into a valid tensor—hence the "setting an array element with a sequence" error.
Additional Fixes for a Functional Regression Model
Beyond fixing the input data, there are a few other tweaks to make your linear regression model behave as expected:
- Flexible Placeholder Shapes: Don't hardcode the batch size in your placeholders. Using
[None, 4]forxand[None, 1]forylets your model handle any batch size, not just 10 samples. - Remove Sigmoid from Output Layer: Sigmoid squashes values to the 0-1 range, which is terrible for regression tasks where your outputs are large continuous numbers (like 148, 85, etc.). We'll use a linear activation (no activation function) for the output layer instead.
- Consistent Epoch Count: Your original code defines
hm_epochs=10000but loops up to 100000—let's align these for clarity.
Corrected Full Code
import tensorflow as tf # Fixed input data: last sample now has 4 elements (matches others) INPUT_XOR = [ [1,72,50,33.6], [1,66,31,26.6], [1,64,32,23.3], [1,66,21,28.1], [1,40,33,43.1], [1,74,30,25.6], [1,50,26,31.0], [1,0,29,35.3], [1,70,53,30.5], [1,96,54,0] # Fixed: added the leading 1 to match other samples ] OUTPUT_XOR = [[148],[85],[183],[89],[137],[116],[78],[115],[197],[125]] n_nodes_hl1 = 10 n_nodes_hl2 = 1 batch_size = 100 # Flexible placeholders (None = any batch size) x = tf.placeholder('float', [None, 4]) y = tf.placeholder('float', [None, 1]) def train_neural_network(x): hidden_1_layer = { 'weights': tf.Variable(tf.random_uniform([4, n_nodes_hl1], -1.0, 1.0)), 'biases': tf.Variable(tf.zeros([n_nodes_hl1])) } output_layer = { 'weights': tf.Variable(tf.random_uniform([n_nodes_hl1, n_nodes_hl2], -1.0, 1.0)), 'biases': tf.Variable(tf.zeros([n_nodes_hl2])) } l1 = tf.add(tf.matmul(x, hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # Removed sigmoid activation for regression output output = tf.add(tf.matmul(l1, output_layer['weights']), output_layer['biases']) prediction = output cost = tf.reduce_mean(tf.squared_difference(prediction, y)) optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost) hm_epochs = 100000 # Aligned with loop range with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): sess.run(optimizer, feed_dict={x: INPUT_XOR, y: OUTPUT_XOR}) if epoch % 10000 == 0: c = sess.run(cost, feed_dict={x: INPUT_XOR, y: OUTPUT_XOR}) print(f'Epoch: {epoch} completed out of {hm_epochs}, Cost: {c:.4f}') train_neural_network(x)
Key Changes Explained
- Fixed Input Data: The last sample in
INPUT_XORnow has 4 elements, matching the rest of the dataset—this resolves the original ValueError. - Flexible Placeholders: Using
Nonefor the first dimension lets you train with different batch sizes later if needed. - Linear Output: Removing the sigmoid ensures your model can predict the full range of your target values instead of being stuck between 0 and 1.
- Consistent Epochs: The epoch count is now aligned between the variable and the loop, making the code easier to read.
内容的提问来源于stack exchange,提问作者Vijay Prabakaran
相关产品推荐
相关产品推荐

