- Python Deep Learning Cookbook
- Indra den Bakker
- 250字
- 2021-07-02 15:43:16
How to do it...
- Import libraries as follows:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
SEED = 2017
- Load the dataset:
data = pd.read_csv('Data/winequality-red.csv', sep=';')
y = data['quality']
X = data.drop(['quality'], axis=1)
- Split the dataset into training and testing:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=SEED)
- Normalize the input data:
scaler = StandardScaler().fit(X_train)
X_train = pd.DataFrame(scaler.transform(X_train))
X_test = pd.DataFrame(scaler.transform(X_test))
- Define the model and optimizer and compile:
model = Sequential()
model.add(Dense(1024, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dense(512, activation='relu'))
# Output layer
model.add(Dense(1, activation='linear'))
# Set optimizer
opt = SGD()
# Compile model
model.compile(loss='mse', optimizer=opt, metrics=['accuracy'])
- Set the hyperparameters and train the model:
n_epochs = 500
batch_size = 256
history = model.fit(X_train.values, y_train, batch_size=batch_size, epochs=n_epochs, validation_split=0.2, verbose=0)
- Predict on the test set:
predictions = model.predict(X_test.values)
print('Test accuracy: {:f>2}%'.format(np.round(np.sum([y_test==predictions.flatten().round()])/y_test.shape[0]*100, 2)))
- Plot the training and validation accuracy:
plt.plot(np.arange(len(history.history['acc'])), history.history['acc'], label='training')
plt.plot(np.arange(len(history.history['val_acc'])), history.history['val_acc'], label='validation')
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy ')
plt.legend(loc=0)
plt.show()
The following graph is obtained:

Figure 2.12: Training and validation accuracy
We should focus on the validation accuracy and use early stopping to stop the training after around 450 epochs. This results in the highest validation accuracy. in the sections Improving generalization with regularization and A`dding dropout to prevent overfitting, we will introduce techniques to prevent overfitting. By using these techniques, we can create deeper models without overfitting on the training data.
推薦閱讀
- Instant Apache Stanbol
- 軟件界面交互設計基礎
- Java入門很輕松(微課超值版)
- Rake Task Management Essentials
- 名師講壇:Java微服務架構(gòu)實戰(zhàn)(SpringBoot+SpringCloud+Docker+RabbitMQ)
- C++ 從入門到項目實踐(超值版)
- Linux:Embedded Development
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- Illustrator CC平面設計實戰(zhàn)從入門到精通(視頻自學全彩版)
- PHP 7從零基礎到項目實戰(zhàn)
- Python Web自動化測試設計與實現(xiàn)
- Solr權(quán)威指南(下卷)
- Learning iOS Penetration Testing
- 軟件自動化測試實戰(zhàn)解析:基于Python3編程語言
- Mastering MeteorJS Application Development