4-regressor_example.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. To know more or get code samples, please visit my website:
  3. https://mofanpy.com/tutorials/
  4. Or search: 莫烦Python
  5. Thank you for supporting!
  6. """
  7. # please note, all tutorial code are running under python3.5.
  8. # If you use the version like python2.7, please modify the code accordingly
  9. # 4 - Regressor example
  10. import numpy as np
  11. np.random.seed(1337) # for reproducibility
  12. from keras.models import Sequential
  13. from keras.layers import Dense
  14. import matplotlib.pyplot as plt
  15. # create some data
  16. X = np.linspace(-1, 1, 200)
  17. np.random.shuffle(X) # randomize the data
  18. Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
  19. # plot data
  20. plt.scatter(X, Y)
  21. plt.show()
  22. X_train, Y_train = X[:160], Y[:160] # first 160 data points
  23. X_test, Y_test = X[160:], Y[160:] # last 40 data points
  24. # build a neural network from the 1st layer to the last layer
  25. model = Sequential()
  26. model.add(Dense(units=1, input_dim=1))
  27. # choose loss function and optimizing method
  28. model.compile(loss='mse', optimizer='sgd')
  29. # training
  30. print('Training -----------')
  31. for step in range(301):
  32. cost = model.train_on_batch(X_train, Y_train)
  33. if step % 100 == 0:
  34. print('train cost: ', cost)
  35. # test
  36. print('\nTesting ------------')
  37. cost = model.evaluate(X_test, Y_test, batch_size=40)
  38. print('test cost:', cost)
  39. W, b = model.layers[0].get_weights()
  40. print('Weights=', W, '\nbiases=', b)
  41. # plotting the prediction
  42. Y_pred = model.predict(X_test)
  43. plt.scatter(X_test, Y_test)
  44. plt.plot(X_test, Y_pred)
  45. plt.show()