转载的原博客地址如下:
http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
下面是对该博客的几个关键点的记录:
1、可以设置随机数种子的时候,建议设置随机数种子,方便结果的复现.
- from keras.models import Sequential
- from keras.layers import Dense
- import numpy
- # fix random seed for reproducibility
- seed = 7
- numpy.random.seed(seed)
2、
toy 数据的地址如下:http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data
加载数据的代码:
- # load pima indians dataset
- dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
- # split into input (X) and output (Y) variables
- X = dataset[:,0:8]
- Y = dataset[:,8]
- # create model
- 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'))
4、编译模型,就是自动将我们定义的代码,使用后端的代码tensorflow或theano去实现
- # Compile model
- model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
5、训练模型
- # Fit the model
- model.fit(X, Y, nb_epoch=150, batch_size=10)
6、评估模型
- # evaluate the model
- scores = model.evaluate(X, Y)
- print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
7、进行预测
- # calculate predictions
- predictions = model.predict(X)
- # round predictions
- rounded = [round(x) for x in predictions]
- print(rounded)
=============================================================
完整代码如下:
- # Create first network with Keras
- from keras.models import Sequential
- from keras.layers import Dense
- import numpy
- import sys
- # fix random seed for reproducibility
- seed = 7
- numpy.random.seed(seed)
- # load pima indians dataset
- dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
- # split into input (X) and output (Y) variables
- X = dataset[:,0:8]
- Y = dataset[:,8]
- # create model
- 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'))
- # Compile model
- model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy','binary_crossentropy'])
- # Fit the model
- model.fit(X, Y, nb_epoch=150, batch_size=10, verbose=2)
- # evaluate the model
- scores = model.evaluate(X, Y)
- print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
- # calculate predictions
- predictions = model.predict(X)
- #print predictions
- # round predictions
- rounded = [round(x) for x in predictions]
- #print(rounded)