class MarkovChain:
def init(self, order=1, binary_data=None, partial_links=False):
self.order = order
self.partial_links = partial_links
self.binary_data = binary_data if binary_data is not None else self.generate_binary_data()
self.transition_matrix = self.generate_transition_matrix()
code
def generate_binary_data(self, size=100):
return [random.choice([0, 1]) for _ in range(size)]
def generate_transition_matrix(self):
matrix_size = 2 ** self.order
matrix = np.zeros((matrix_size, 3), dtype='object')
for i in range(matrix_size):
# Fill matrix with random probabilities, making sure
# the sum of probabilities in each row equals 1
if self.partial_links:
prob = random.uniform(0, 1)
state_str = format(i, f'0{self.order}b') # Convert integer to binary string
matrix[i] = [state_str, prob, 1 - prob]
else:
state_str = format(i, f'0{self.order}b') # Convert integer to binary string
matrix[i][0] = state_str
matrix[i][1:] = np.random.dirichlet(np.ones(matrix_size), size=1)
return matrix
def print_transition_matrix(self):
print("Transition Matrix:")
for row in self.transition_matrix:
print("{}\t{:.2f}\t{:.2f}".format(row[0], row[1], row[2]))
def generate_data(self, length=100):
generated_data = []
initial_state = random.choice(range(2 ** self.order))
state = initial_state
for _ in range(length):
generated_data.append(state & 1) # Get the last binary digit
transition_probabilities = self.transition_matrix[state][1:]
state = np.random.choice(range(2 ** self.order), p=transition_probabilities)
return generated_data
Assistant
markov_chain = MarkovChain(order=3, partial_links=True)
markov_chain.order = 2
markov_chain.partial_links = True
markov_chain.print_transition_matrix()
generated_data = markov_chain.generate_data(length=100)
print("Generated Data:", generated_data)
fix:Traceback (most recent call last):
File "C:\Users\bboyp\OneDrive\Рабочий стол\markov1\main.py", line 55, in
generated_data = markov_chain.generate_data(length=100)
File "C:\Users\bboyp\OneDrive\Рабочий стол\markov1\main.py", line 46, in generate_data
state = np.random.choice(range(2 ** self.order), p=transition_probabilities)
File "mtrand.pyx", line 944, in numpy.random.mtrand.RandomState.choice
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
It seems the issue is related to the array transition_probabilities having mixed data types (object, float). This is because when initializing the transition matrix using the partial_links=True option, the matrix is filled with mixed data types. When you switch back to markov_chain.partial_links = True, it still uses that transition matrix with mixed data types, which causes the error.
To fix this issue, you can adjust the generate_transition_matrix method to ensure proper data types, and make sure that, after modifying MarkovChain instance attributes, you regenerate the transition matrix:
python
def generate_transition_matrix(self):
matrix_size = 2 ** self.order
matrix = np.zeros((matrix_size, 2), dtype=float)
state_strings = []
for i in range(matrix_size):
# Fill matrix with random probabilities, making sure
# the sum of probabilities in each row equals 1
if self.partial_links:
prob = random.uniform(0, 1)
state_str = format(i, f'0{self.order}b') # Convert integer to binary string
matrix[i] = [prob, 1 - prob]
else:
matrix[i] = np.random.dirichlet(np.ones(matrix_size), size=1)
state_strings.append(state_str)
return state_strings, matrix
Now generate_transition_matrix returns a tuple of two arrays: one with state strings, and the other with float dtype information. To access the transition probabilities, you need to change the generate_data method as well:
python
def generate_data(self, length=100):
generated_data = []
initial_state = random.choice(range(2 ** self.order))
state = initial_state
for _ in range(length):
state_str = self.transition_matrix[0][state]
generated_data.append(int(state_str[-1])) # Get the last binary digit
transition_probabilities = self.transition_matrix[1][state]
state = np.random.choice(range(2 ** self.order), p=transition_probabilities)
return generated_data
Finally, after modifying MarkovChain attributes, regenerate the transition matrix and update its instance: