Advertisement
Guest User

Untitled

a guest
Feb 21st, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.34 KB | None | 0 0
  1.  
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib.colors as mclr
  5.  
  6. from keras import layers
  7. from keras import models
  8.  
  9. def genData(size=500):
  10. size1 = size//2
  11. size2 = size - size1
  12.  
  13. t1 = np.random.rand(size1)
  14. x1 = np.asarray([i * np.math.cos(i*2*np.math.pi) + (np.random.rand(1)-1)/2*i for i in t1])
  15. y1 = np.asarray([i * np.math.sin(i*2*np.math.pi) + (np.random.rand(1)-1)/2*i for i in t1])
  16. data1 = np.hstack((x1, y1))
  17. label1 = np.zeros([size1, 1])
  18. div1 = round(size1*0.8)
  19.  
  20. t2 = np.random.rand(size2)
  21. x2 = np.asarray([-i * np.math.cos(i*2*np.math.pi) + (np.random.rand(1)-1)/2*i for i in t2])
  22. y2 = np.asarray([-i * np.math.sin(i*2*np.math.pi) + (np.random.rand(1)-1)/2*i for i in t2])
  23. data2 = np.hstack((x2, y2))
  24. label2 = np.ones([size2, 1])
  25. div2 = round(size2*0.8)
  26.  
  27. div = div1 + div2
  28. order = np.random.permutation(div)
  29.  
  30. train_data = np.vstack((data1[:div1], data2[:div2]))
  31. test_data = np.vstack((data1[div1:], data2[div2:]))
  32. train_label = np.vstack((label1[:div1], label2[:div2]))
  33. test_label = np.vstack((label1[div1:], label2[div2:]))
  34. return (train_data[order, :], train_label[order, :]), (test_data, test_label)
  35.  
  36.  
  37. def drawResults(data, label, prediction):
  38. p_label = np.array([round(x[0]) for x in prediction])
  39. plt.scatter(data[:, 0], data[:, 1], s=30, c=label[:, 0], cmap=mclr.ListedColormap(['red', 'blue']))
  40. plt.scatter(data[:, 0], data[:, 1], s=10, c=p_label, cmap=mclr.ListedColormap(['red', 'blue']))
  41. plt.grid()
  42. plt.show()
  43.  
  44.  
  45. (train_data, train_label), (test_data, test_label) = genData()
  46.  
  47. #В данном месте необходимо создать модель и обучить ее
  48. model = models.Sequential()
  49. model.add(layers.Dense(16, activation='relu', input_shape=(2,)))
  50. model.add(layers.Dense(16, activation='relu'))
  51. model.add(layers.Dense(16, activation='relu'))
  52. model.add(layers.Dense(1, activation='sigmoid'))
  53.  
  54. model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
  55. H = model.fit(train_data, train_label, epochs=40, batch_size=10, validation_data=(test_data, test_label))
  56.  
  57. #Получение ошибки и точности в процессе обучения
  58. loss = H.history['loss']
  59. val_loss = H.history['val_loss']
  60. acc = H.history['acc']
  61. val_acc = H.history['val_acc']
  62. epochs = range(1, len(loss) + 1)
  63.  
  64. #Построение графика ошибки
  65. plt.plot(epochs, loss, 'bo', label='Training loss')
  66. plt.plot(epochs, val_loss, 'b', label='Validation loss')
  67. plt.title('Training and validation loss')
  68. plt.xlabel('Epochs')
  69. plt.ylabel('Loss')
  70. plt.legend()
  71. plt.show()
  72.  
  73. #Построение графика точности
  74. plt.clf()
  75. plt.plot(epochs, acc, 'bo', label='Training acc')
  76. plt.plot(epochs, val_acc, 'b', label='Validation acc')
  77. plt.title('Training and validation accuracy')
  78. plt.xlabel('Epochs')
  79. plt.ylabel('Accuracy')
  80. plt.legend()
  81. plt.show()
  82.  
  83. #Получение и вывод результатов на тестовом наборе
  84. results = model.evaluate(test_data, test_label)
  85. print(results)
  86.  
  87. #Вывод результатов бинарной классификации
  88. all_data = np.vstack((train_data, test_data))
  89. all_label = np.vstack((train_label, test_label))
  90. pred = model.predict(all_data)
  91. drawResults(all_data, all_label, pred)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement