# Python中Keras深度学习库的回归教程

2018-02-11 14:07:41来源:https://cloud.tencent.com/developer/article/1040680作者:极客头条人点击

Keras 是一个深度学习库，它封装了高效的数学运算库 Theano 和 TensorFlow。

2017 年 3 月

1.问题描述

，并将其保存到当前工作目录，命名为 housing.csv。

2.开发基准神经网络模型

import numpy
import pandas
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

UCI机器学习库中的数据集实际上不是 CSV 格式，而是用空格分隔两个属性。我们可以使用pandas库轻松加载这个数据集。然后，分离输入（X）和输出（Y）属性，以便更容易使用 Keras 和 scikit-learn 进行建模。

dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,0:13]
Y = dataset[:,13]

Keras 包装函数需要一个函数作为参数。这个必须被定义的函数负责创建要评估的神经网络模型。

# define base model
def baseline_model():
# create model
model = Sequential()
# Compile model
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)

kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(estimator, X, Y, cv=kfold)
print("Results: %.2f (%.2f) MSE" % (results.mean(), results.std()))

Baseline: 31.64 (26.82) MSE
3.建模标准化数据集

# evaluate model with standardized dataset
numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=baseline_model, epochs=50, batch_size=5,verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(pipeline, X, Y, cv=kfold)
print("Standardized: %.2f (%.2f) MSE" % (results.mean(), results.std()))

Standardized: 29.54 (27.87) MSE

4.调整神经网络拓扑

4.1。评估层数更深的网络拓扑

# define the model
def larger_model():
# create model
model = Sequential()
# Compile model
return model

13 inputs -> [13 -> 6] -> 1 output

numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=larger_model, epochs=50, batch_size=5,verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(pipeline, X, Y, cv=kfold)
print("Larger: %.2f (%.2f) MSE" % (results.mean(), results.std()))

Larger: 22.83 (25.33) MSE

4.2。评估层宽更宽的网络拓扑

# define wider model
def wider_model():
# create model
model = Sequential()
# Compile model
return model

13 inputs -> [20] -> 1 output

numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=wider_model, epochs=100, batch_size=5,verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(pipeline, X, Y, cv=kfold)
print("Wider: %.2f (%.2f) MSE" % (results.mean(), results.std()))

Wider: 21.64 (23.75) MSE

2