Advertisement
here2share

# calc_pi_by_nth_digit_pattern_recog_test_two.py

Mar 29th, 2023
1,274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.12 KB | None | 0 0
  1. # calc_pi_by_nth_digit_pattern_recog_test_two.py
  2.  
  3. # written by Kirk Lawrence
  4.  
  5. import pdb
  6. import math
  7. import random
  8. import os, sys
  9. import ast
  10. from itertools import combinations
  11.  
  12. try:
  13.     # Python2
  14.     from Tkinter import *
  15.     from urllib2 import urlopen
  16. except ImportError:
  17.     # Python3
  18.     from tkinter import *
  19.     from urllib.request import urlopen
  20.    
  21. def print_each_at_x(vars_list, nnn=22):
  22.     sss = ''
  23.     for var in vars_list:
  24.         n = nnn
  25.         if isinstance(var, list):
  26.             var = ' '.join([str(v) for v in var])
  27.         else:
  28.             var = str(var)
  29.         if len(var) > n - 4:
  30.             n *= 2
  31.         var = (var + ' ' * n)[:n-1] + ' '
  32.         sss += var
  33.     print(sss.rstrip())   # to print a new line at the end
  34.  
  35. okay  = 1
  36.  
  37. root = Tk()
  38. root.withdraw()
  39.  
  40. def cpbd():
  41.     try:
  42.         # t = root.selection_get(selection="CLIPBOARD")
  43.         t = root.clipboard_get()
  44.         return t
  45.     except:
  46.         return []
  47.     # root.clipboard_clear()
  48.     # root.destroy()
  49. 0
  50.    
  51. def gym(): # for that pseudo neural exercise
  52.     if prediction != yn:           
  53.         for node in nodes:
  54.             weights[node, yn] += 1
  55.            
  56. 0
  57. def guess(data): # guess before training for this data
  58.     ttt = []
  59.     for z in enumerate(data):
  60.         s = '%d:%s'%z
  61.         ttt.append(s)
  62.    
  63.     nodes.extend(list(combinations(ttt, 2))) ### length-3
  64.     # print (len(nodes))
  65.        
  66.     ttt = {0: 0, 1: 0}
  67.     for node in nodes:
  68.         try:
  69.             ttt[0] += weights[node, 0]
  70.             ttt[1] += weights[node, 1]
  71.         except:
  72.             weights[node, 0] = 0
  73.             weights[node, 1] = 0
  74.            
  75.     p = 0
  76.     if ttt[0] < ttt[1]:
  77.         p = 1
  78.    
  79.     return p
  80. 0
  81.  
  82. ###
  83.  
  84. summary = 1
  85.  
  86. # import numpy as np ### very much recommended 2018
  87.  
  88. # 5000 places of pi
  89. pi = '''
  90. 31415926535897932...'''.strip()
  91. Lpi = len(pi)
  92.  
  93. print ("Gathering Data, Please Wait...")
  94.  
  95. right_answers = []
  96. wrong_answers = []
  97. for i in range(Lpi):
  98.     right_answers += [(1, str(i) + pi[i])]
  99.     wrong_answers += [(0, str(pi[i]))]
  100.    
  101. const_wrong_answers = {}
  102. for i in range(10):
  103.     const_wrong_answers[str(i)] = []
  104.     for j in range(1,10):
  105.         const_wrong_answers[str(i)] += [str((i + j) % 10)]
  106.  
  107. print ('Pattern Recognition Sequence Is Ready To Commence...')
  108.  
  109. if 1: # for testing
  110.  
  111.     random.seed(0)
  112.    
  113.     rush = 5000
  114.    
  115.     const_zzz = (right_answers + wrong_answers) * 10
  116.    
  117.     right = 0
  118.     wrong = 0
  119.            
  120.     percent = '0.0'
  121.    
  122.     gain = 0.0
  123.     prev_gain = gain
  124.    
  125.     weights = {}
  126.     weight_errors = {}
  127.        
  128.     bias = {}
  129.    
  130.     zzz = const_zzz[:]
  131.     random.shuffle(zzz)
  132.    
  133.     final = 0
  134.    
  135.     end = len(zzz)
  136.     count_to_end = 0
  137.    
  138.     go = 0
  139.     while zzz:
  140.         z = zzz.pop(0)
  141.        
  142.         yn, data = z
  143.         if not yn:
  144.             str_digit = const_wrong_answers[data].pop(0)
  145.             const_wrong_answers[data].append(str_digit)
  146.             data += str_digit
  147.        
  148.         data = data.zfill(5)
  149.                
  150.         nodes = []
  151.        
  152.         prediction = guess(data)
  153.        
  154.         gym()
  155.                    
  156.         if prediction == yn:
  157.             right += 1
  158.             count_to_end += 1
  159.         else:
  160.             wrong += 1
  161.             count_to_end = 0
  162.         if not (go+1)%rush:
  163.             if okay: ### for other tests
  164.                
  165.                 percent = '{:.1f}'.format((100.0/(right+wrong))*right)
  166.                 gain = max(gain,float(percent))
  167.                
  168.                 t = str(go+1).zfill(8)
  169.                 print ('.')
  170.                 print_each_at_x([['. >>> actual vs prediction =', [yn, prediction]] ,['::: Remaining', max(0,end-count_to_end)], final])
  171.                 print_each_at_x([['.',data , ':::','test#',t], ['::: wrong =',wrong], ['::: right =',right], [':::','{:.1f}'.format(gain)+' / '+percent+'%']])
  172.                 print ('.')
  173.                
  174.                 right = 0
  175.                 wrong = 0
  176.            
  177.             if count_to_end >= end or int(t) > 2500000:
  178.                 break                  
  179.        
  180.         zzz.append(z)
  181.                
  182.         go += 1
  183.            
  184.  
  185. print ('.','*'*10,'End Of Cycle','*'*10)
  186. print ('.')
  187.  
  188. '''
  189. if summary:
  190.     ttt = list(weights.items())
  191.     ttt.sort(key=lambda x: (x[-1],x[0]), reverse=1)
  192.     for t in ttt[:1000]:
  193.         print ('.',t)
  194.     print ('.')
  195.     for t in ttt[-1000:]:
  196.         print ('.',t)
  197.     print ('.')
  198.     print ('.',len(ttt))
  199. '''
  200.  
  201. def calc_pi_digit(num):
  202.     for pi_digit in range(10):
  203.         del nodes[:]
  204.         data = str(num) + str(pi_digit)
  205.         data = data.zfill(5)
  206.         prediction = guess(data)
  207.         if prediction:
  208.             break
  209.     return pi_digit
  210.  
  211. for n in range(Lpi):
  212.     pi_digit = calc_pi_digit(n)
  213.     wrong = ''
  214.     sss = f"... the {n}th digit of pi is {pi[n]}"
  215.     if pi[n] == str(pi_digit):
  216.         s = "CORRECT !!!"
  217.     else:
  218.         s = "\t*** Wrong"
  219.         wrong = f", not {pi_digit}"
  220.     print(s + sss + wrong)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement