1

I am running the code below but it's giving me an error about arrays. I have tried to find a solution and somehow understand the problem but I couldn't solve the problem. Here is my code:

import tensorflow as tf
import pandas as pa
import numpy as np


iris = pa.read_csv("iris.csv", names = ['F1', 'F2', 'F3', 'F4', 'class'])
print(iris.head(5))

iris['class'].value_counts()

#mapping data

A1 = np.asarray([1,0,0])
A2 = np.asarray([0,1,0])
A3 = np.asarray([0,0,1])
Irises = {'Iris-setosa' : A1, 'two' : A2, 'Iris-virginica' : A3}
iris['class'] = iris['class'].map(Irises)


#Mjesanje podataka 
iris = iris.iloc[np.random.permutation(len(iris))]

print(iris.head(10))
iris = iris.reset_index(drop=True)
print(iris.head(10))

#splitting data into training and testing
x_train = iris.ix[0:100,['F1', 'F2', 'F3', 'F4']]
y_train = iris.ix[0:100,['class']]
x_test = iris.ix[101:, ['F1', 'F2', 'F3', 'F4']]
y_test = iris.ix[101:, ['class']]


print(x_train.tail(5))
print(y_train.tail(5))

print(x_test.tail(5))
print(y_test.tail(5))

n_nodes_hl1 = 150
n_nodes_hl2 = 150


n_classes = 3 # U ovom slucaju tri, 1-> Iris-setosa, Iris-versicolo, Iris-virginica
batch_size = 50 # Da li ima neko optimalno rijesenje koliko uzeti?

x = tf.placeholder('float', shape = [None, 4]) # 4 featrues 
y = tf.placeholder('float', shape = [None, n_classes]) # 3 classes 


def neural_network_model(data):
    hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([4, n_nodes_hl1])),
                    'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                    'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

    output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])),
                    'biases': tf.Variable(tf.random_normal([n_classes]))}


    l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases']) #(input_data * weights) + biases
    l1 = tf.nn.relu(l1) #activation function, im using rectified 

    l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']), hidden_layer_2['biases'])
    l2 = tf.nn.relu(l2)

    output_layer = tf.matmul(l2, output_layer['weights'] + output_layer['biases'])

    return output_layer


def train_neural_network(x):
    prediction = neural_network_model(x)
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y)) #loss
    optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)

    #koliko puta ce ici back
    hm_epoch = 10
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables()) 
        for step in range(hm_epoch):                
            _, c = sess.run([optimizer, cross_entropy], feed_dict={x: x_train, y:[t for t in y_train.as_matrix()]})
            print(c)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
        #prediction = sess.run(accuracy, feed_dict=(x: x_test, y:[t for t in y_test.as_matrix()]))
        #print(prediction)

train_neural_network(x)

And i get this error:

Traceback (most recent call last): File "NeuralNet.py", line 92, in train_neural_network(x) File "NeuralNet.py", line 83, in train_neural_network _, c = sess.run([optimizer, cross_entropy], feed_dict={x: x_train, y:[t for t in y_train.as_matrix()]}) File "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 717, in runrun_metadata_ptr) File "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 888, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "/home/jusuf/anaconda3/lib/python3.5/site-packages/numpy/core/numeric.py", line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence.

2 Answers 2

1

One action that produces this error is assigning a list to an array element:

In [498]: x=np.zeros(3)
In [499]: x
Out[499]: array([ 0.,  0.,  0.])
In [500]: x[0] = [1,2,3]
....
ValueError: setting an array element with a sequence.

Since the error is in a np.asarray(subfeed_val, dtype=subfeed_dtype) statement it is more likely that it is doing something like:

In [502]: np.array([[1,2,3],[1,2]], dtype=int)
ValueError: setting an array element with a sequence.

It's still the problem of trying to put a sequence of numbers into one slot.

Looking further up the error stack, the error is in:

sess.run([optimizer, cross_entropy], feed_dict={x: x_train, y:[t for t in y_train.as_matrix()]})

I don't think it has to do with the assignment to c.

sess.run is a tensorflow function that I know nothing about.

================

the error stack, properly formatted is

Traceback (most recent call last): 
File "NeuralNet.py", line 92, in train_neural_network(x) 
File "NeuralNet.py", line 83, in train_neural_network
   _, c = sess.run([optimizer, cross_entropy], feed_dict={x: x_train, y:[t for t in y_train.as_matrix()]}) 
File "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 717, in    
    runrun_metadata_ptr) 
File "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 888, in 
   _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) 
File "/home/jusuf/anaconda3/lib/python3.5/site-packages/numpy/core/numeric.py", line 482, in 
   asarray return array(a, dtype, copy=False, order=order) 
ValueError: setting an array element with a sequence.

I'd suggest reviewing the tensorflow documentation, and make sure that inputs to this function are correct. Focus on allowed types, and if arrays, pay attention to dimensions, shape, and dtype.

Sign up to request clarification or add additional context in comments.

Comments

0

Error message is;

ValueError: setting an array element with a sequence.

Explains that: You're trying to set an array element with a sequence. Well, where is the mistake, see below;

c = sess.run([optimizer, cross_entropy]

So tell me what is the "c" . It's probably a float, integer or whatever. But I am pretty sure it is not an array. That's why you are receiving an exception above.

But if you want to print out that array, you can do directly;

print(sess.run([optimizer, cross_entropy]) instead of run print(c)

As far as I saw from your code, you are not using "c" anywhere.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.