深度学习:python教程 实践(二)8和9章节

时间:2021-06-10 22:35:12
需要看原文连接的请点这里

第8章
其实本章重点在代码上,内容其实理解起来是这样的

模型训练的参数调整有时会比较随意,所以测试很重要,
怎么测呢
把现有真实数据分成两份,一份用来训练,一份用来测试准确率
即8:2分,或者7:3分
两种方法是边算边测,算完再测的概念,只要理解这些,再看看代码,模仿写写即可

9章
也是在做模型的验算,不同的的是,这次用的是sklearn进行验算,
还多了一种方法 网格搜索测试,在多组参数中选出最优组合
同第八章,简略看看概念,重点把代码复写一便

以下附上部分代码
get_data.py

import random
import numpy as np

def get_range(range_one, range_two):
list_one = []
for x in range(range_one):
list_two = []
for y in range(range_two):
if y == 0:
value = random.randint(0, 10)
else:
value = random.randint(0, 1)
list_two.append(value)
list_one.append(list_two)
return np.array(list_one)
kr_test02.py
from get_data import get_range
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.grid_search import GridSearchCV
import numpy


def create_model(optimizer='rmsprop', init='glorot_uniform'):
# create model
model = Sequential()
model.add(Dense(8, input_dim=1, kernel_initializer=init, activation='relu'))
model.add(Dense(4, kernel_initializer=init, activation='relu'))
model.add(Dense(1, kernel_initializer=init, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model

test_data_np = get_range(1000, 2)
X = test_data_np[:, 0:1]
Y = test_data_np[:, 1]
# create model
model = KerasClassifier(build_fn=create_model)
# grid search epochs, batch size and optimizer
optimizers = ['rmsprop', 'adam']
init = ['glorot_uniform', 'normal', 'uniform']
# epochs = numpy.array([50, 100, 150])
# batches = numpy.array([5, 10, 20])
epochs = numpy.array([20, 50, 80])
batches = numpy.array([2, 5, 80])
param_grid = dict(optimizer=optimizers, nb_epoch=epochs, batch_size=batches, init=init)
grid = GridSearchCV(estimator=model, param_grid=param_grid)
grid_result = grid.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
for params, mean_score, scores in grid_result.grid_scores_:
print("%f (%f) with: %r" % (scores.mean(), scores.std(), params))