ANN实施过度拟合

时间:2019-05-12 17:13:59

标签: python machine-learning deep-learning

我是ML领域的新手,正在学习它,我通过按照教程制作了模型,但结果准确性总是很快就会升至100%。根据我的理解,我在网上搜索并发现有关模型过度拟合的问题。我使用的数据集来自UCI网站名为“印度肝病患者数据集”的数据。该数据集包含大约600个观察点。

我的问题是我如何克服数据中的过度拟合问题。任何帮助将不胜感激,谢谢。

import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import scikitplot as skplt
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

df = pd.read_csv("C:/TF/TEST/ILDP.csv")

df["ag_ratio"].fillna("0.6", inplace=True)

df.isnull().sum()

print(df.head())

LD, NLD = df['is_patient'].value_counts()

df_sex = pd.get_dummies(df['gender'])
df_new = pd.concat([df, df_sex], axis=1)

Droop_gender = df_new.drop(labels=['gender'], axis=1)
Droop_gender.columns = ['age', 'tot_bilirubin', 'direct_bilirubin', 'tot_proteins', 'albumin', 'ag_ratio',
                        'sgpt', 'sgot', 'alkphos', 'Female', 'Male', 'is_patient']

X = Droop_gender.drop('is_patient', axis=1)
y = Droop_gender['is_patient']

print(X.shape)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

classifier = Sequential()  # Initialising the ANN

classifier.add(Dense(units=16, kernel_initializer='uniform', activation='relu', input_dim=11))
classifier.add(Dense(units=8, kernel_initializer='uniform', activation='relu'))
classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))
classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))

# compile ANN
classifier.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

# Fitting the data
histroy = classifier.fit(X_train, y_train, batch_size=20, epochs=50)


y_pred = classifier.predict(X_test)
y_pred = [1 if y >= 0.5 else 0 for y in y_pred]

print(classification_report(y_test, y_pred))

1 个答案:

答案 0 :(得分:1)

您的模型过度拟合令人鼓舞,因为这意味着您的模型具有学习能力。现在,您必须逐渐减少模型的容量,以使其更好地推广。我的建议是添加正则化。

在某些完全连接的层之间添加退出层:

classifier.add(Dense(units=16, kernel_initializer='uniform', activation='relu', input_dim=11))
classifier.add(keras.layers.Dropout(0.5))
classifier.add(Dense(units=8, kernel_initializer='uniform', activation='relu'))

您可以在任何层之间添加这些dropout层,但是在具有更多神经元的层之间添加更好。

如果效果不好,您可以尝试减轻体重。这是文档中的示例:

from keras import regularizers
model.add(Dense(64, input_dim=64,
                kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01)))

尽管先尝试kernel_regularize或activity_regularizer。无论如何,它们都应该大致相同。尝试调整,看看不同的参数如何变化。最后,这是很多黑魔法,因此您必须尝试一下。祝你好运!