转载的原博客地址如下:
http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
下面是对该博客的几个关键点的记录:
1、可以设置随机数种子的时候,建议设置随机数种子,方便结果的复现.
- from keras.models import Sequential
- from keras.layers import Dense
- import numpy
-
- seed = 7
- numpy.random.seed(seed)
2、
toy 数据的地址如下:http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data
加载数据的代码:
-
- dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
-
- X = dataset[:,0:8]
- Y = dataset[:,8]
3、定义模型
-
- model = Sequential()
- model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
- model.add(Dense(8, init='uniform', activation='relu'))
- model.add(Dense(1, init='uniform', activation='sigmoid'))
说明:Dense是全连接网络,只有第一层需要设定输入层的结点个数,其他都不需要
4、编译模型,就是自动将我们定义的代码,使用后端的代码tensorflow或theano去实现
-
- model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
5、训练模型
-
- model.fit(X, Y, nb_epoch=150, batch_size=10)
6、评估模型
-
- scores = model.evaluate(X, Y)
- print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
7、进行预测
-
- predictions = model.predict(X)
-
- rounded = [round(x) for x in predictions]
- print(rounded)
=============================================================
完整代码如下:
-
- from keras.models import Sequential
- from keras.layers import Dense
- import numpy
- import sys
-
- seed = 7
- numpy.random.seed(seed)
-
- dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
-
- X = dataset[:,0:8]
- Y = dataset[:,8]
-
- model = Sequential()
- model.add(Dense(12, input_dim=8, init='normal', activation='relu'))
- model.add(Dense(8, init='normal', activation='relu'))
- model.add(Dense(1, init='normal', activation='sigmoid'))
-
- model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy','binary_crossentropy'])
-
- model.fit(X, Y, nb_epoch=150, batch_size=10, verbose=2)
-
- scores = model.evaluate(X, Y)
- print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
-
- predictions = model.predict(X)
-
-
- rounded = [round(x) for x in predictions]
-