Pandas DataFrame 和 Keras

22

我正在尝试使用Keras在Python中进行情感分析。为了这样做,我需要对我的文本进行单词嵌入。当我尝试将数据适应于我的模型时,问题就出现了:

model_1 = Sequential()
model_1.add(Embedding(1000,32, input_length = X_train.shape[0]))
model_1.add(Flatten())
model_1.add(Dense(250, activation='relu'))
model_1.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

我的训练数据的形状是

(4834,)

这是一个Pandas系列对象。当我尝试拟合我的模型并用其他数据进行验证时,我会遇到以下错误:

And is a Pandas series object. When I try to fit my model and validate it with some other data I get this error:


model_1.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=2, batch_size=64, verbose=2)

数值错误:检查模型输入时出错:期望的嵌入_1_input形状为(无,4834),但得到形状为(4834,1)的数组

我该如何重塑我的数据以适用于Keras?我一直在尝试使用np.reshape,但是我无法使用该函数放置None元素。

提前感谢。

4个回答

27

None是指在训练中预期的行数,因此您不能定义它。此外,Keras需要一个numpy数组作为输入,而不是pandas数据帧。首先使用df.values将df转换为numpy数组,然后执行np.reshape((-1, 4834))。请注意,应使用np.float32。如果您要在GPU上进行训练,则这一点非常重要。


8

https://pypi.org/project/keras-pandas/

最简单的方法是使用keras_pandas包将pandas数据帧适配到keras。下面的代码是该软件包文档中的一个通用示例。

from keras import Model
from keras.layers import Dense

from keras_pandas.Automater import Automater
from keras_pandas.lib import load_titanic

observations = load_titanic()

# Transform the data set, using keras_pandas
categorical_vars = ['pclass', 'sex', 'survived']
numerical_vars = ['age', 'siblings_spouses_aboard', 'parents_children_aboard', 'fare']
text_vars = ['name']

auto = Automater(categorical_vars=categorical_vars, numerical_vars=numerical_vars, text_vars=text_vars,
 response_var='survived')
X, y = auto.fit_transform(observations)

# Start model with provided input nub
x = auto.input_nub

# Fill in your own hidden layers
x = Dense(32)(x)
x = Dense(32, activation='relu')(x)
x = Dense(32)(x)

# End model with provided output nub
x = auto.output_nub(x)

model = Model(inputs=auto.input_layers, outputs=x)
model.compile(optimizer='Adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train model
model.fit(X, y, epochs=4, validation_split=.2)

2
看起来 keras_pandas 的开发已经在2018年停止了,目前只支持tensorflow 1.11版本。而 tensorflow 最新版本是2.3。 - tillmo

2

为使此方法可行,需要使用特定版本的Pandas。如果您使用当前版本(截至2018年8月20日),则此方法将失败。

请回滚您的Pandas和Keras(pip uninstall ....),然后安装如下特定版本:

python -m pip install pandas==0.19.2

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接