Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2015
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.18 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import random
  4. from tabulate import tabulate
  5. import matplotlib.mlab as mlab
  6.  
  7. precision = 100000000000
  8.  
  9. def MarkovChain(n,s) :
  10.     """
  11.  
  12.   """
  13.     matrix = []
  14.     for l in range(n) :
  15.         lineLst = []
  16.         sum = 0
  17.         crtPrec = precision
  18.         for i in range(n-1) :
  19.             val = random.randrange(crtPrec)
  20.             sum += val
  21.             lineLst.append(float(val)/precision)
  22.             crtPrec -= val
  23.         lineLst.append(float(precision - sum)/precision)
  24.         matrix2 = matrix.append(lineLst)
  25.     print("The intial probability matrix.")    
  26.     print(tabulate(matrix2))
  27.     baseprob = []
  28.     baseprob2 = []
  29.     baseprob3 = []
  30.     baseprob4 = []
  31.  
  32.     for i in range(1,s): #changed to do a range 1-s instead of 1000
  33.  
  34.  #must use the loop variable here, not s (s is always the same)
  35.         matrix_n = np.linalg.matrix_power(matrix2, i)
  36.         baseprob.append(matrix_n.item(0))
  37.         baseprob2.append(matrix_n.item(1))
  38.         baseprob3.append(matrix_n.item(2))
  39.  
  40.     baseprob = np.array(baseprob)
  41.     baseprob2 = np.array(baseprob2)
  42.     baseprob3 = np.array(baseprob3)
  43.     baseprob4 = np.array(baseprob4)
  44.          
  45.     # Here I tried to make a histogram using the plt.hist() command, but the normed=True doesn't work like I assumed it would.
  46.     '''    
  47.   plt.hist(baseprob, bins=20, normed=True)
  48.   plt.show()
  49.   '''
  50.    
  51.     #Here I tried to make a histogram using the method from the second link in my post.
  52.     # The code runs, but then the graph that is outputted isn't doesn't have the relative frequency on the y axis.
  53.     '''
  54.    n, bins, patches = plt.hist(baseprob, bins=30,normed=True,facecolor = "green",)
  55.    y = mlab.normpdf(bins,mu,sigma)
  56.    plt.plot(bins,y,'b-')
  57.    plt.title('Main Plot Title',fontsize=25,horizontalalignment='right')
  58.    plt.ylabel('Count',fontsize=20)
  59.    plt.yticks(fontsize=15)
  60.    plt.xlabel('X Axis Label',fontsize=20)
  61.    plt.xticks(fontsize=15)
  62.    plt.show()
  63.    '''
  64.     # Here I tried to make a histogram using the method seen in the Stackoverflow question I mentioned.
  65.     # The figure that pops out looks correct in terms of the axes, but no actual data is posted. Instead the error below is shown in the console.
  66.     # AttributeError: 'list' object has no attribute 'size'
  67.    
  68.    
  69.     fig = plt.figure()
  70.     ax = fig.add_subplot(111)
  71.     ax.hist(baseprob, weights=np.zeros_like(baseprob)+1./ baseprob.size)
  72.     n, bins, patches = ax.hist(baseprob, bins=100, normed=1, cumulative=0)
  73.     ax.set_xlabel('Bins', size=20)
  74.     ax.set_ylabel('Frequency', size=20)
  75.     ax.legend
  76.     plt.show()
  77.    
  78.    
  79.     print("The final probability matrix.")
  80.     print(tabulate(matrix_n))
  81.     matrixTranspose = zip(*matrix_n)
  82.     evectors = np.linalg.eig(matrixTranspose)[1][:,0]
  83.     print("The steady state vector is:")
  84.     print(evectors)
  85.    
  86.    
  87.    
  88.    
  89.    
  90.  
  91. MarkovChain(5, 1000)
  92.  
  93.  
  94. ----------------------------------------------------------------
  95.  
  96.  
  97.  runfile('C:/Users/Raleigh/Documents/Python Scripts/MarkovChainSO.py', wdir='C:/Users/Raleigh/Documents/Python Scripts')
  98. The intial probability matrix.
  99.  
  100.  
  101. Traceback (most recent call last):
  102.  
  103.   File "<ipython-input-52-15a2bf632b19>", line 1, in <module>
  104.     runfile('C:/Users/Raleigh/Documents/Python Scripts/MarkovChainSO.py', wdir='C:/Users/Raleigh/Documents/Python Scripts')
  105.  
  106.   File "C:\Users\Raleigh\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
  107.     execfile(filename, namespace)
  108.  
  109.   File "C:\Users\Raleigh\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
  110.     exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
  111.  
  112.   File "C:/Users/Raleigh/Documents/Python Scripts/MarkovChainSO.py", line 97, in <module>
  113.     MarkovChain(5, 1000)
  114.  
  115.   File "C:/Users/Raleigh/Documents/Python Scripts/MarkovChainSO.py", line 41, in MarkovChain
  116.     matrix_n = np.linalg.matrix_power(matrix2, i)
  117.  
  118.   File "C:\Users\Raleigh\Anaconda3\lib\site-packages\numpy\matrixlib\defmatrix.py", line 171, in matrix_power
  119.     raise ValueError("input must be a square array")
  120.  
  121. ValueError: input must be a square array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement