无法将NumPy数组转换为张量(不支持的对象类型float)

时间:2020-06-12 15:00:28

标签: python pandas numpy tensorflow keras

我尝试了多种在线发布的解决方案,但无济于事。我在代码中缺少什么吗?

我的数据包含多个float变量,其中一个字符串变量是OneHotEncoded。

我的模特:

import numpy as np
import pandas as pd
import tensorflow as tf

dataset = pd.read_csv('Processed Temp.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [0])], remainder = 'passthrough')
X = np.array(ct.fit_transform(X))

X = np.asarray(X)
y = np.asarray(y)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=19, activation='relu'))
ann.add(tf.keras.layers.Dense(units=19, activation='relu'))
ann.add(tf.keras.layers.Dense(units=1))

ann.compile(optimizer = 'adam', loss = 'mean_squared_error')
ann.fit(X_train, y_train ,batch_size = 32, epochs = 100)

y_pred = ann.predict(X_test)
np.set_printoptions(precision=2)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))

错误:

ValueError                                Traceback (most recent call last)
<ipython-input-14-4d1188c7d3d7> in <module>()
      1 
----> 2 ann.fit(X_train, y_train ,batch_size = 32, epochs = 100)

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

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

感谢所有我能得到的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您能否提供与此问题相关的数据集?没有数据集,很难说你的变量或方法是否错误。无论如何要将任何数组转换为张量,我们可以使用“tensorflow.convert_to_tensor()”语法。 arr=np.array([[1,2,3,4,5],[6,7,8,9,1]]) arr=tf.convert_to_tensor(arr) print(type(arr)) 这会将 numpy 数组转换为张量。 如需更多信息,请访问 here