brainstocker.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-"
  3. """
  4. BrAInStocker - 2020 - by psy (epsylon@riseup.net)
  5. You should have received a copy of the GNU General Public License along
  6. with BrAInStocker; if not, write to the Free Software Foundation, Inc., 51
  7. Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  8. """
  9. import random, time, os
  10. import csv
  11. import pandas as pd
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14. from sklearn.linear_model import LinearRegression
  15. from sklearn.datasets import make_regression
  16. from sklearn import linear_model
  17. print(75*"=")
  18. print(" ____ _ ___ ____ _ _ ")
  19. print("| __ ) _ __ / \ |_ _|_ __ / ___|| |_ ___ ___| | _____ _ __ ")
  20. print("| _ \| '__/ _ \ | || '_ \\___ \| __/ _ \ / __| |/ / _ \ '__|")
  21. print("| |_) | | / ___ \ | || | | |___) | || (_) | (__| < __/ | ")
  22. print("|____/|_|/_/ \_\___|_| |_|____/ \__\___/ \___|_|\_\___|_| ")
  23. print(" ")
  24. print(75*"=","\n")
  25. print("Can you 'predict' the next random number?\n")
  26. print(75*"=")
  27. print ("\n[Info] Starting prediction...\n")
  28. store_dataset = "dataset/"
  29. if not os.path.exists(store_dataset):
  30. os.mkdir(store_dataset)
  31. r = 0
  32. match = False
  33. numrange = input(" -Set the maximum number for a random number (PRESS ENTER = 100): ")
  34. if not numrange:
  35. numrange = 100
  36. try:
  37. numrange = int(numrange)
  38. except:
  39. numrange = 100
  40. maxrange = input(" -Set the maximum number of random numbers to be generate (PRESS ENTER = 1000) (STOP = CTRL+z): ")
  41. if not maxrange:
  42. maxrange = 1000
  43. try:
  44. maxrange = int(maxrange)
  45. except:
  46. maxrange = 1000
  47. print("\n[Info] Generating "+ str(maxrange)+ " random numbers...\n")
  48. with open('dataset/dataset.csv', 'w', newline='') as f:
  49. w = csv.writer(f)
  50. w.writerow(["ROUND", "Time", "Number"])
  51. f.close()
  52. def advance_round(r):
  53. r = r + 1
  54. return r
  55. def generate_random_number():
  56. for x in range(numrange):
  57. n = random.randint(0,numrange)
  58. return n
  59. def check_current_time():
  60. t = int(round(time.time() * 1000))
  61. return t
  62. def format_digits(num):
  63. nr = int(len(str(numrange)))
  64. num = num.zfill(nr)
  65. return num
  66. print("="*40)
  67. print("ROUND: TIME: NUMBER:")
  68. print("-"*40)
  69. for a in range(0, maxrange):
  70. r = advance_round(r)
  71. t = str(check_current_time())
  72. n = str(generate_random_number())
  73. with open('dataset/dataset.csv', 'a', newline='') as f:
  74. w = csv.writer(f)
  75. w.writerow([r, t, n])
  76. print ("[", str(r).zfill(5), "] [", t, "] -> [", str(format_digits(str(n))),"]")
  77. df = pd.read_csv('dataset/dataset.csv')
  78. x = df['Number']
  79. y = df['Time']
  80. X, y = make_regression(n_samples=maxrange, n_features=2, noise=0.0)
  81. model = linear_model.LinearRegression()
  82. try:
  83. model.fit(X, y)
  84. Xnew = [[check_current_time(), generate_random_number()]]
  85. ynew = model.predict(Xnew)
  86. prediction = str(Xnew[0][1])
  87. prediction = format_digits(prediction)
  88. nextnum = str(generate_random_number())
  89. nextnum = format_digits(nextnum)
  90. print("\n"+"="*40)
  91. print("[AI] PREDICTION : [ %s ]" % prediction)
  92. print("="*40)
  93. print("[AI] NEXT NUMBER: [ %s ] " % nextnum)
  94. print("="*40+"\n")
  95. if prediction == nextnum:
  96. print("[Info] MATCH !!! ;-)\n")
  97. match = True
  98. else:
  99. print("[Info] NOT MATCH ...\n")
  100. match = False
  101. fig = plt.figure()
  102. x_values=np.array(x,dtype=np.float64).reshape(1,-1)
  103. y_values=np.array(y,dtype=np.float64).reshape(1,-1)
  104. ax = fig.add_subplot(111)
  105. ax.axes.get_yaxis().set_visible(False)
  106. xy_prediction=(prediction, prediction)
  107. xy_nextnum=(nextnum, nextnum)
  108. ax.scatter(xy_prediction, xy_prediction, 20, c = 'red')
  109. ax.scatter(xy_nextnum, xy_nextnum, 20, c = 'green')
  110. ax.scatter(x_values, y_values, 5, c = 'blue')
  111. ax.set_xlabel("DATETIME: ["+str(t)+ " ]")
  112. ax.set_ylabel("")
  113. if match == False:
  114. header = "PREDICTION: [ "+prediction+" ] -> [ "+str(nextnum)+ " ] [NOT MATCH]\n"
  115. else:
  116. header = "PREDICTION: [ "+prediction+" ] -> [ "+str(nextnum)+ " ] [MATCH !!!]\n"
  117. plt.title(header)
  118. print("="*40+"\n")
  119. if not os.path.exists("dataset/"+str(t)+'_'+str(prediction)+'_'+str(nextnum)+"-prediction.png"):
  120. fig.savefig("dataset/"+str(t)+'_'+str(prediction)+'_'+str(nextnum)+"-prediction.png")
  121. print("[Info] Generated 'prediction' image at: dataset/"+str(t)+'_'+str(prediction)+'_'+str(nextnum)+"-prediction.png\n")
  122. else:
  123. print("[Info] You have previously saved this 'prediction'...\n")
  124. fig.canvas.set_window_title("BrAInStocker | Linear Regression Predictor | by psy (https://03c8.net)")
  125. plt.show()
  126. except:
  127. print("="*40+"\n")
  128. print("[Info] This cannot be considered a valid collection for [AI] Linear Regression. Exiting...\n")