ValueError:无法在 Python 中将 NumPy 数组转换为张量(不支持的对象类型 int)

数据挖掘 Python 神经网络 喀拉斯 熊猫 麻木的
2022-02-16 18:45:44

我已经为神经网络编写了以下代码来对数据集执行回归,但是我得到了一个ValueError. 我查看了不同的答案,他们建议使用df = df.values来获取一个 numpy 数组。我试过了,但它仍然产生同样的错误。如何解决这个问题?

代码

from keras import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split

#Define Features and Label
features = ['posted_by', 'under_construction', 'rera', 'bhk_no.', 'bhk_or_rk',
            'square_ft', 'ready_to_move', 'resale', 'longitude',
            'latitude'] 

X=train[features].values
y=train['target(price_in_lacs)'].values

#Train Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 23, shuffle = True)

#Model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='random_normal', input_dim = 10))
model.add(Dense(1, activation = 'relu', kernel_initializer='random_normal'))

#Compiling the neural network
model.compile(optimizer = Adam(learning_rate=0.1) ,loss='mean_squared_logarithmic_error', metrics =['mse'])

#Fitting the data to the training dataset  
model.fit(X_train,y_train, batch_size=256, epochs=100, verbose=0)

错误

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).
4个回答

它们无法被X_train解析y_trainpandas.core.series.Series

尝试将它们转换为如下列表:

X=train[features].to_list()

y=train['target(price_in_lacs)'].to_list()

在拟合模型之前,训练数据写入以下 2 行:

X_train=np.asarray(X_train).astype(np.int)

y_train=np.asarray(y_train).astype(np.int)

要将 numpy 数组转换为张量,

import tensor as tf
#Considering y variable holds numpy array
y_tensor = tf.convert_to_tensor(y, dtype=tf.int64) 

#您可以使用任何最适合的可用数据类型 - https://www.tensorflow.org/api_docs/python/tf/dtypes/DType

这可能是由于您的某些列可能没有完整的整数值,在拟合之前您应该转换它

X = np.asarray(X).astype(np.int_)
Y = np.array(Y).astype(np.int_)