1. Keras Demo2
前节的Keras Demo代码:
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD,Adam
from keras.utils import np_utils
from keras.datasets import mnist
def load_data():
(x_train,y_train),(x_test,y_test)=mnist.load_data()
number=10000
x_train=x_train[0:number]
y_train=y_train[0:number]
x_train=x_train.reshape(number,28*28)
x_test=x_test.reshape(x_test.shape[0],28*28)
x_train=x_train.astype('float32')
x_test=x_test.astype('float32')
y_train=np_utils.to_categorical(y_train,10)
y_test=np_utils.to_categorical(y_test,10)
x_train=x_train
x_test=x_test
x_train=x_train/255
x_test=x_test/255
return (x_train,y_train),(x_test,y_test)
(x_train,y_train),(x_test,y_test)=load_data()
model=Sequential()
model.add(Dense(input_dim=28*28,units=633,activation='sigmoid'))
model.add(Dense(units=633,activation='sigmoid'))
model.add(Dense(units=633,activation='sigmoid'))
model.add(Dense(units=10,activation='softmax'))
model.compile(loss='mse',optimizer=SGD(lr=0.1),metrics=['accuracy'])
model.fit(x_train,y_train,batch_size=100,epochs=20)
result= model.evaluate(x_test,y_test)
print('TEST ACC:',result[1])
Keras Demo中的结果不是很好,看一下在Training Data上的结果:
result= model.evaluate(x_test,y_test)
result2 = model.evaluate(x_train,y_train,batch_size=10000)
print('TEST ACC:',result[1])
print('TRAIN ACC:',result2[1])
结果如下:
TEST ACC: 0.1135
TRAIN ACC: 0.1128000020980835
说明在Training Data上结果也不好,接下来开始调参:
loss function
分类问题mse不适合,将loss mse function 改为categorical_crossentropy
model.compile(loss='categorical_crossentropy',optimizer=SGD(lr=0.1),metrics=['accuracy'])
结果如下:
TEST ACC: 0.8488
TRAIN ACC: 0.8611000180244446
batch_size
batch_size从100改为10000,得到的结果不好。
model.fit(x_train,y_train,batch_size=10000,epochs=20)
结果如下:
TEST ACC: 0.101
TRAIN ACC: 0.10320000350475311
改为1,无法并行,速度变得很慢。
model.fit(x_train,y_train,batch_size=1,epochs=20)
deep layer
加10层,没有train起来。
for _ in range(10):
model.add(Dense(units=689,activation='sigmoid'))
结果如下:
TEST ACC: 0.101
TRAIN ACC: 0.10320000350475311
activation functon
把sigmoid都改为relu,发现现在train的accuracy就爬起来了,接近100%,在Test Data上也表现很好。
结果如下:
TEST ACC: 0.9556
TRAIN ACC: 0.9998000264167786
normalize
如果不进行normalize,把255去掉,得到的结果又不好了,这些细节也很重要。
# x_train=x_train/255
# x_test=x_test/255
结果如下:
TEST ACC: 0.098
TRAIN ACC: 0.10010000318288803
optimizer
把SGD(lr=0.1)改为Adam,然后再跑一次,用adam的时候最后收敛的地方差不多,但是上升的速度变快了。
结果如下:
TEST ACC: 0.9667
TRAIN ACC: 1.0
Random noise
加上noise之后,结果不好,overfitting了。
x_test=np.random.normal(x_test)
结果如下:
TEST ACC: 0.4986
TRAIN ACC: 0.9991000294685364
dropout
dropout 加在每个hidden layer之后,dropout加入之后,train的效果会变差,然而test的正确率提升了。
model.add(Dense(input_dim=28*28,units=689,activation='relu'))
model.add(Dropout(0.7))
model.add(Dense(units=689,activation='relu'))
model.add(Dropout(0.7))
model.add(Dense(units=689,activation='relu'))
model.add(Dropout(0.7))
model.add(Dense(units=10,activation='softmax'))
结果如下:
TEST ACC: 0.594
TRAIN ACC: 0.9894000291824341
2. FizzBuzz
题目描述:
给你100以内的数. 如果这个数被3整除,打印fizz.
如果这个数被5整除,打印buzz.
如果这个数能同时被3和5整除,打印fizz buzz.
FizzBuzz是一个很有意思的题目,如果用深度学习的方法来做的话,可以用如下代码实现。
数据准备:
对数字101到1000都做了数据标注,即训练数据xtrain.shape=(900,10),
每一个数字都是用二进位来表示,第一个数字是101,用二进位来表示即为[1,0,1,0,0,1,1,0,0,0],
每一位表示(2^{n-1}),(n)表示左数第几位。现在一共有四个case,[一般,Fizz,Buzz,Fizz Buzz],所以y_train.shape=(900,10),对应的维度用1表示,其他都为0。
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD,Adam
import numpy as np
def fizzbuzz(start, end):
x_train, y_train=[],[]
for i in range(start, end+1):
num = i
tmp = [0]*10
j = 0
while num:
tmp[j] = num & 1
num = num >> 1
j += 1
x_train.append(tmp)
if i % 3 == 0 and i % 5 == 0:
y_train.append([0,0,0,1])
elif i % 3 == 0:
y_train.append([0,1,0,0])
elif i % 5 == 0:
y_train.append([0,0,1,0])
else:
y_train.append([1,0,0,0])
return np.array(x_train), np.array(y_train)
x_train,y_train = fizzbuzz(101, 1000) #打标记函数
x_test,y_test = fizzbuzz(1, 100)
model = Sequential()
model.add(Dense(input_dim=10, output_dim=100))
model.add(Activation('relu'))
model.add(Dense(output_dim=4))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=20, nb_epoch=100)
result = model.evaluate(x_test, y_test, batch_size=1000)
print('Acc:',result[1])
最后的结果不是100%,所以我们将hidden neure从100改为1000,结果就是100%了。
model.add(Dense(input_dim=10, output_dim=1000))