2017-01-12 4 views
1

Я запускаю код ниже, но он дает мне ошибку в массивах. Я попытался найти решение и как-то понять проблему, но я не мог решить проблему. Вот мой код:Что такое решение python дает мне «ValueError: установка элемента массива с последовательностью».

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) 

И я получаю эту ошибку:

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.

ответ

0

сообщение об ошибке;

ValueError: setting an array element with a sequence. 

Объясняет, что: вы пытаетесь установить элемент массива с последовательностью. Ну, где ошибка, см. Ниже;

c = sess.run([optimizer, cross_entropy] 

Так скажите мне, что такое «c». Вероятно, это float, integer или что-то еще. Но я уверен, что это не массив. Вот почему вы получаете исключение выше.

Но если вы хотите распечатать этот массив, вы можете сделать это напрямую;

print(sess.run([optimizer, cross_entropy]) вместо бега print(c)

Насколько я видел из своего кода, вы не используете «C» в любом месте.

1

Одно действие, которое производит эта ошибка присвоения значения к элементу массива:

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. 

Поскольку ошибка в np.asarray(subfeed_val, dtype=subfeed_dtype) заявлении, более вероятно, что он делает что-то вроде:

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

По-прежнему проблема в том, чтобы поместить последовательность чисел в один слот.

Глядя дальше стека ошибок, ошибка в:

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

Я не думаю, что это связано с назначением на c.

sess.run является функцией tensorflow, о которой я ничего не знаю.

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

стек ошибок, правильно отформатирован является

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. 

Я хотел бы предложить обзор документации tensorflow, и убедитесь, что входы в эту функцию верны. Сосредоточьтесь на разрешенных типах и массивах, обратите внимание на размеры, форму и тип.

Смежные вопросы