值错误:提供的元素过多。最多需要4个,但收到8个

时间:2019-09-25 13:26:20

标签: python

我是数据科学的初学者。我想在数据中使用张量流来通过梯度下降优化theta参数(变量)。

在我想将theta变成恒定向量的那一行中,我遇到了一个错误。

import csv
import tensorflow as tf
path=r"C:\Users\USER\Desktop\PRSA_data_2010.1.1-2014.12.31.csv"
f=open(path,encoding="utf8")
dataset=[]
header=f.readline().strip().split(',')
for line in f:
    line = line.split(',')
    dataset.append(line)
dataset = [d for d in dataset if d[5] !="NA"]
def feature(datum):
     feat=[1,float(datum[7]),float(datum[8]), float(datum[10])]
    return feat
x=[feature(d)for d in dataset]
y=[float(d[5]) for d in dataset]
y=tf.constant(y, shape=[len(y),1])
k=len(x[0])
def MSE(x,y,thetha):
   return tf.reduce_mean((tf.matmul(x,thetha)-y)**2)
theta=tf.Variable(tf.constant([0,0]*k,shape=[k,1]))

然后在最后一行中出现此错误

ValueError                                Traceback (most recent call last)
<ipython-input-16-307fdd57da6c> in <module>
----> 1 theta=tf.Variable(tf.constant([0,0]*k,shape=[k,1]))

~\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in constant_v1(value, dtype, shape, name, verify_shape)
    178   """
    179   return _constant_impl(value, dtype, shape, name, verify_shape=verify_shape,
--> 180                         allow_broadcast=False)
    181 
    182 

~\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
    282       tensor_util.make_tensor_proto(
    283           value, dtype=dtype, shape=shape, verify_shape=verify_shape,
--> 284           allow_broadcast=allow_broadcast))
    285   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    286   const_tensor = g.create_op(

~\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
    526         raise ValueError(
    527             "Too many elements provided. Needed at most %d, but received %d" %
--> 528             (shape_size, nparray.size))
    529 
    530   tensor_proto = tensor_pb2.TensorProto(

ValueError: Too many elements provided. Needed at most 4, but received 8

1 个答案:

答案 0 :(得分:0)

我没有tensorflow,但是如果它的行为类似于Numpy,则您指定的形状与值中的项目数不匹配。您的异常消息表示k = 4并且您指定了一个包含四个项目的形状,而您的值([0,0]*k)包含八个项目:

In [13]: k = 4

In [14]: value = [0,0]*k

In [15]: value
Out[15]: [0, 0, 0, 0, 0, 0, 0, 0]

In [16]: np.asarray(value).reshape([k,1])
Traceback (most recent call last):

  File "<ipython-input-16-43f917d6ea82>", line 1, in <module>
    np.asarray(value).reshape([k,1])

ValueError: cannot reshape array of size 8 into shape (4,1)