Advertisement
here2share

# calc_pi_by_nth_digit_pattern_recog_test_three.py

Mar 29th, 2023 (edited)
727
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.15 KB | None | 0 0
  1. # calc_pi_by_nth_digit_pattern_recog_test_three.py
  2.  
  3. # combination of 3 nodes instead of 2
  4. # written by Kirk Lawrence
  5.  
  6. import pdb
  7. import math
  8. import random
  9. import os, sys
  10. import ast
  11. from itertools import combinations
  12.  
  13. try:
  14.     # Python2
  15.     from Tkinter import *
  16.     from urllib2 import urlopen
  17. except ImportError:
  18.     # Python3
  19.     from tkinter import *
  20.     from urllib.request import urlopen
  21.    
  22. def print_each_at_x(vars_list, nnn=22):
  23.     sss = ''
  24.     for var in vars_list:
  25.         n = nnn
  26.         if isinstance(var, list):
  27.             var = ' '.join([str(v) for v in var])
  28.         else:
  29.             var = str(var)
  30.         if len(var) > n - 4:
  31.             n *= 2
  32.         var = (var + ' ' * n)[:n-1] + ' '
  33.         sss += var
  34.     print(sss.rstrip())   # to print a new line at the end
  35.  
  36. okay  = 1
  37.  
  38. root = Tk()
  39. root.withdraw()
  40.  
  41. def cpbd():
  42.     try:
  43.         # t = root.selection_get(selection="CLIPBOARD")
  44.         t = root.clipboard_get()
  45.         return t
  46.     except:
  47.         return []
  48.     # root.clipboard_clear()
  49.     # root.destroy()
  50. 0
  51.    
  52. def gym(): # for that pseudo neural exercise
  53.     if prediction != yn:           
  54.         for node in nodes:
  55.             weights[node, yn] += 1
  56.            
  57. 0
  58. def guess(data): # guess before training for this data
  59.     ttt = []
  60.     for z in enumerate(data):
  61.         s = '%d:%s'%z
  62.         ttt.append(s)
  63.    
  64.     nodes.extend(list(combinations(ttt, 3)))
  65.     # print (len(nodes))
  66.        
  67.     ttt = {0: 0, 1: 0}
  68.     for node in nodes:
  69.         try:
  70.             ttt[0] += weights[node, 0]
  71.             ttt[1] += weights[node, 1]
  72.         except:
  73.             weights[node, 0] = 0
  74.             weights[node, 1] = 0
  75.            
  76.     p = 0
  77.     if ttt[0] < ttt[1]:
  78.         p = 1
  79.    
  80.     return p
  81. 0
  82.  
  83. ###
  84.  
  85. summary = 1
  86.  
  87. # import numpy as np ### very much recommended 2018
  88.  
  89. # 5000 places of pi
  90. pi = '''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) > 500000:
  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