简体   繁体   English

我不断收到此错误:无法将 NumPy 数组转换为张量(不支持的 object 类型 numpy.ndarray)

[英]I keep getting this error: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)

as a continuation to Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)作为Tensorflow 的延续 - ValueError: 无法将 NumPy 数组转换为张量(不支持的 object 类型浮点数)

I had a similar issue where I had the following error我有一个类似的问题,我有以下错误

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

I followed the different suggestions but it does not seem to solve my problem.我遵循了不同的建议,但似乎并没有解决我的问题。

all the values below are <class 'numpy.ndarray'>下面的所有值都是 <class 'numpy.ndarray'>

train_inputs=df_train_title_train
train_targets=y_train.to_numpy()
validation_inputs=df_train_title_test
validation_targets=y_test.to_numpy()

shapes are (63586,), (63586, 9), (7066,), (7066, 9) respectively where 9 is the number of class I am trying to classify形状分别是 (63586,), (63586, 9), (7066,), (7066, 9) 其中 9 是我要分类的 class 的数量

# Set the input and output sizes
input_size = 64
output_size = 9
# Use same hidden layer size for both hidden layers. Not a necessity.
hidden_layer_size = 64


# define how the model will look like
model = tf.keras.Sequential([
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # 1st hidden layer
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # 2nd hidden layer
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # 2nd hidden layer
    tf.keras.layers.Dense(output_size, activation='softmax') # output layer
])


model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])


### Training
# That's where we train the model we have built.

# set the batch size
batch_size = 10

# set a maximum number of training epochs
max_epochs = 10

# fit the model
# note that this time the train, validation and test data are not iterable
model.fit(train_inputs, # train inputs
          train_targets, # train targets
          batch_size=batch_size, # batch size
          epochs=max_epochs, # epochs that we will train for (assuming early stopping doesn't kick in)
          validation_data=(validation_inputs, validation_targets), # validation data
          verbose = 2 # making sure we get enough information about the training process
          )  

Finally the error looks like this.最后错误看起来像这样。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-75-10183099f9ec> in <module>()
      6           epochs=max_epochs, # epochs that we will train for (assuming early stopping doesn't kick in)
      7           validation_data=(validation_inputs, validation_targets), # validation data
----> 8           verbose = 2 # making sure we get enough information about the training process
      9           )  

16 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
     96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)
     99 
    100 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

It is possible that your data has numpy array as elements instead of float.您的数据可能将 numpy 数组作为元素而不是浮点数。 You should analyse your data.你应该分析你的数据。

Following example reproduces the same problem:以下示例重现了相同的问题:

import numpy as np
import pandas as pd
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential

data = [
  [np.asarray([.1]),np.asarray([.2]),np.asarray([.3])],
  [np.asarray([.1]),np.asarray([.2]),np.asarray([.3])],
  [np.asarray([.1]),np.asarray([.2]),np.asarray([.3])],
]
X_train = pd.DataFrame(data=data, columns=["x1","x2","x3"])
y_train = pd.DataFrame(data=[1,0,1], columns=["y"])


print(X_train)
>>       x1     x2     x3
>> 0  [0.1]  [0.2]  [0.3]
>> 1  [0.1]  [0.2]  [0.3]
>> 2  [0.1]  [0.2]  [0.3]


print(X_train.dtypes)
>> x1    object
>> x2    object
>> x3    object
>> dtype: object


model = Sequential()
model.add(Dense(1, input_dim=X_train.shape[1], activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train.to_numpy(), y_train, epochs=3)

>> ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

If the above dataframe is fixed as follows, the MLP model works just fine:如果上述 dataframe 固定如下,则 MLP model 工作正常:

from pandas.core.common import flatten
X_train = X_train.apply(lambda x: pd.Series(flatten(x)))

print(X_train)
>>     x1   x2   x3
>> 0  0.1  0.2  0.3
>> 1  0.1  0.2  0.3
>> 2  0.1  0.2  0.3


model = Sequential()
model.add(Dense(1, input_dim=X_train.shape[1], activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train.to_numpy(), y_train, epochs=3, verbose=3)
>> Epoch 1/3
>> Epoch 2/3
>> Epoch 3/3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将 NumPy 数组转换为张量(不支持的 object 类型 numpy.ndarray)错误 - Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) error 错误:无法将 NumPy 数组转换为张量(不支持 object 类型 numpy.ndarray) - Error: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) ValueError:无法将 NumPy 数组转换为数组大小超过 4000 的张量(不支持的对象类型 numpy.ndarray) - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) with array size exceeding 4000 ValueError:无法将 NumPy 数组转换为 CNN 分类上的张量(不支持的 object 类型 numpy.ndarray) - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) on CNN classifiction ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) in Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) in Tensorflow ValueError:无法使用 tensorflow CNN 将 NumPy 数组转换为张量(不支持 object 类型 numpy.ndarray) - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) with tensorflow CNN "ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). In TensorFlow CNN for image classification - "ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). In TensorFlow CNN for image classification ValueError:无法将 NumPy 数组转换为张量(不支持的 object 类型 numpy.ndarray)。在 jupyternotebook - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).in jupyternotebook ValueError:无法将 NumPy 数组转换为张量(不支持的 object 类型 numpy.ndarray)。 试图预测特斯拉股票 - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). in trying to predict tesla stock 尝试执行 model.fit() 时出现 ValueError -:无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray) - ValueError when trying to execute model.fit() -: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM