Python神经网络中的形状问题

时间:2020-08-12 21:47:28

标签: python tensorflow machine-learning keras reshape

我有以下数据框:https://raw.githubusercontent.com/markamcgown/Projects/master/df_model.csv

在下面的最后一个代码块中的“ ---> 11 history = model.fit”处,出现错误“ ValueError:sequence_8的输入0与该层不兼容::预期的min_ndim = 3,找到ndim = 2。收到完整形状:[None,26]“

为什么期望至少有3个维度,我如何才能自动在下面的代码中始终显示正确的形状?

import keras
import pandas as pd
from tensorflow.keras.models import Sequential
from sklearn.model_selection import train_test_split
from keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D
from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional
from keras.layers import Dense, Dropout, Flatten, Reshape, GlobalAveragePooling1D

path = r'C:\Users\<your_local_directory>\df_model.csv'
#Import raw data file with accelerometer data
df_model = pd.read_csv(path)
df_model

enter image description here

y_column = 'Y_COLUMN'
x = df_model.drop(y_column, inplace=False, axis=1).values
y = df_model[y_column].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=42)
def create_model(num_features, num_classes, dropout=0.3,
                loss="mean_absolute_error", optimizer="rmsprop"):
    model = Sequential()
    model.add(Conv1D(100, 10, activation='relu', input_shape=(None,num_features)))
    model.add(Conv1D(100, 10, activation='relu'))
    model.add(MaxPooling1D(2))
    model.add(Conv1D(160, 10, activation='relu'))
    model.add(Conv1D(160, 10, activation='relu'))
    model.add(LSTM(160, return_sequences=True))
    model.add(LSTM(160, return_sequences=True))
    model.add(GlobalAveragePooling1D())
    model.add(Dropout(dropout))
    model.add(Dense(num_classes, activation='softmax'))
    model.compile(loss=loss, metrics=["mean_absolute_error"], optimizer=optimizer)
    return model
DROPOUT = 0.4
LOSS = "huber_loss"
OPTIMIZER = "adam"

num_time_periods, num_features = x_train.shape[0], x_train.shape[1]

model = create_model(num_features, num_classes=len(set(df_model[y_column])), loss=LOSS, 
                      dropout=DROPOUT, optimizer=OPTIMIZER)
callbacks_list = [keras.callbacks.ModelCheckpoint(filepath='best_model.{epoch:02d}-{val_loss:.2f}.h5',monitor='val_loss', save_best_only=True),keras.callbacks.EarlyStopping(monitor='accuracy', patience=1)]

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

# Hyper-parameters
BATCH_SIZE = 400
EPOCHS = 1

# Enable validation to use ModelCheckpoint and EarlyStopping callbacks.
history = model.fit(x_train,y_train,batch_size=BATCH_SIZE,epochs=EPOCHS,callbacks=callbacks_list,validation_split=0.2,verbose=1)

plt.figure(figsize=(15, 4))
plt.plot(history.history['accuracy'], "g-", label="Training Accuracy")
#plt.plot(history.history['val_accuracy'], "g", label="Accuracy of validation data")
plt.plot(history.history['loss'], "r-", label="Training Loss")
#plt.plot(history.history['val_loss'], "r", label="Loss of validation data")
plt.title('Model Performance')
plt.ylabel('Accuracy & Loss')
plt.xlabel('Epoch')
plt.ylim(0)
plt.legend()
plt.show()

0 个答案:

没有答案