Advertisement
here2share

# calc_pi_by_nth_digit_pattern_recog_test_one.py

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