keras framework is a deep learning of the neural network can be quickly set up and carry out inspection and testing, it is a quick entry software neural network.
Before using keras, you need to install tensorflow.
1, the installation tensorflow
First update pip, pip and the linux yum almost, if the source is not new, it may be time to install the software failure can lead to dependence, failed to install the software.
Run as Administrator cmd window
pip install msgpack python –m pip install –upgrade pip pip install -U --ignore-installed wrapt pip install --upgrade tensorflow pip install tensorflow
2, installation keras
pip install hard
3, build a linear regression neural network
Use the following code attempts to run jupyter notebook.
3.1 generates data
AS NP numpy Import np.random.seed (1337) from the Sequential keras.models # Import neural network layer by layer from keras.layers import Dense # fully connected neural network neurons import matplotlib.pyplot as plt # graphics library
Generating data # X = np.linspace (-1, 1, 200) # in return (-1, 1) the range arithmetic sequence np.random.shuffle (X) # scrambled Y = 0.5 * X + 2 + np.random.normal (0, 0.05, ( 200,)) # Y generate and add noise # Plot plt.scatter (X-, Y) plt.show ()
3.2 specify the training set and test set
X_train, Y_train = X [: 160 ], Y [: 160] # 160 before the training data set data set X_test, Y_test = X [160: ], Y [160:] # 40 sets the test data set to the data
3.3 build neural networks
= the Sequential Model () model.add (the Dense (input_dim =. 1, Units =. 1)) # Selected functions and loss optimizer model.compile (loss = 'mse', optimizer = 'sgd')
Here's loss to the optimizer have many different options, these different functions, will use different algorithms, resulting in speed and accuracy of our model of learning.
3.4 Training Model
print('Training -----------') for step in range(501): cost = model.train_on_batch(X_train, Y_train) if step % 50 == 0: print("After %d trainings, the cost: %f" % (step, cost))
3.5 Test Model
print('\nTesting ------------') cost = model.evaluate(X_test, Y_test, batch_size=40) print('test cost:', cost) W, b = model.layers[0].get_weights() print('Weights=', W, '\nbiases=', b)
3.6 Draw results
Y_pred = model.predict(X_test) plt.scatter(X_test, Y_test) plt.plot(X_test, Y_pred) plt.show()
After descent algorithm through linear regression and gradient, the neural network automatically generating the discrete data, fitting a straight line to become.