python给我的解决方案是"ValueError:设置具有序列的数组元素". [英] What is the solution python gives me "ValueError: setting an array element with a sequence."

查看:62
本文介绍了python给我的解决方案是"ValueError:设置具有序列的数组元素".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行下面的代码,但它给我关于数组的错误.我试图找到一种解决方案并以某种方式理解该问题,但是我无法解决该问题.这是我的代码:

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)

我得到这个错误:

回溯(最近一次通话最后一次):文件"NeuralNet.py",第92行,在 train_neural_network(x)train_neural_network中的文件"NeuralNet.py",第83行 _,c = sess.run([optimizer,cross_entropy],feed_dict = {x:x_train,y:[t代表y_train.as_matrix()中的t)})文件 "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", 在runrun_metadata_ptr文件中的第717行) "/home/jusuf/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", 第888行,在_run np_val = np.asarray(subfeed_val, dtype = subfeed_dtype)文件 "/home/jusuf/anaconda3/lib/python3.5/site-packages/numpy/core/numeric.py", 第482行,呈数组形式 返回array(a,dtype,copy = False,order = order)ValueError:设置具有序列的数组元素.

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.

推荐答案

一个产生此错误的操作是将列表分配给数组元素:

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.

由于错误出现在np.asarray(subfeed_val, dtype=subfeed_dtype)语句中,因此更有可能执行以下操作:

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()]})

我认为这与分配给c无关.

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

sess.run是我一无所知的tensorflow函数.

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.

我建议您阅读tensorflow文档,并确保对此功能的输入正确.重点关注允许的类型,如果是数组,则要注意尺寸,形状和dtype.

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.

这篇关于python给我的解决方案是"ValueError:设置具有序列的数组元素".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆