import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Dropout
import tensorflow as tf
import keras
# 如果使用GPU版TensorFlow,并且在显卡高占用率的情况下训练模型,
# 那要在初始化Session时为其分配固定数量的显存,否则可能会在开始训练的时候直接报错退出
def get_session():
""" Construct a modified tf session.
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
keras.backend.tensorflow_backend.set_session(get_session())
# 生成虚拟数据
x_train = np.random.random((1000,20))
y_train = np.random.randint(2,size=(1000,1))
x_test = np.random.random((100,20))
y_test = np.random.randint(2,size=(100,1))
#第一层为输入层,20个节点
#第二次为64个节点,紧跟着dropout层
#第三层为64个节点,紧跟着dropout层
#第四次为1个节点
model = Sequential()
model.add(Dense(64,input_dim=20,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1,activation='sigmoid'))
model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])
model.fit(x_train,y_train,epochs=20,batch_size=100)
score = model.evaluate(x_test,y_test,batch_size=100)
print('the binary classify result is {}'.format(score))