使用 theano 在 keras 中格式化 X_train

数据挖掘 回归 scikit-学习 喀拉斯 数据格式
2022-02-17 13:01:35

在已经使用 sklearn 之后,我想尝试使用 Keras(Theano 后端)进行回归。

为此,我使用了这个很好的教程http://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/ 并尝试用我自己的替换训练数据。

import numpy
import pandas
import pickle
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import StandardScaler


[X, Y] = pickle.load(open("training_data_1_week_imp_lt_15.pkl", "rb"))


X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size=0.5, random_state=42)
scaler = StandardScaler()
scaler.fit(X_train)  # Don't cheat - fit only on training data
X_train = scaler.transform(X_train)

X_test = scaler.transform(X_test)

print (X_train.shape)


# define base mode
def baseline_model():
    # create model
    model = Sequential()
    model.add(Dense(8, input_dim=8, init='normal', activation='relu'))
    model.add(Dense(1, init='normal'))
    # Compile model
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model


# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# evaluate model with standardized dataset
estimator = KerasRegressor(build_fn=baseline_model, nb_epoch=100, batch_size=5, verbose=0)    

estimator.fit(numpy.array(X_train),y_train)

但是,我收到以下错误:

Exception: Error when checking model target: the list of Numpy arrays that you are 
passing to your model is not the size the model expected. Expected to see 1 
arrays but instead got the following list of 6252 arrays: ...

X的格式是常用的sklearn格式: print (X_train.shape) = (6252, 8)

如何正确格式化输入 X。

我尝试的是转置,但这不起作用。

我也已经在网上搜索过,但找不到解决方案/解释。

谢谢!

编辑:这是一个小示例文件https://ufile.io/8a428

[X, Y] = pickle.load(open("test.pkl", "rb"))
1个回答

我解决了这个问题(仍然把头撞在墙上):

estimator.fit(numpy.array(X_train),numpy.array(y_train))

这行得通。我不确定为什么。错误消息非常具有误导性恕我直言。