Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
scikit_learn_randomforest_to_verilog_pipeline_fragment.py
# rf = scikit-learnのRandomForest
from collections import deque
def get_leaf_labels(tree, depth):
leaf_min_index = 2 ** (depth) - 1
features =[-1] * (2 ** (depth) - 1)
labels = [-1] * 2 ** depth
tree_labels = np.argmax(tree.value.T, axis=0)[0]
queue = deque([(0, 0)])
while len(queue) > 0:
index_tp = queue.popleft()
old_index = index_tp[0]
new_index = index_tp[1]
if old_index == -1:
features[new_index] = 0
if new_index * 2 + 2 < leaf_min_index:
queue.append((-1, new_index * 2 + 1))
queue.append((-1, new_index * 2 + 2))
continue
if tree.feature[old_index] >= 0:
features[new_index] = tree.feature[old_index]
queue.append((tree.children_left[old_index], new_index * 2 + 1))
queue.append((tree.children_right[old_index], new_index * 2 + 2))
continue
if new_index >= leaf_min_index:
labels[new_index - leaf_min_index] = tree_labels[old_index]
else:
features[new_index] = 0
if new_index * 2 + 2 < leaf_min_index:
queue.append((-1, new_index * 2 + 1))
queue.append((-1, new_index * 2 + 2))
left = new_index
right = new_index
while left < leaf_min_index:
#features[left] = 0
left = left * 2 + 1
while right < leaf_min_index:
#features[right] = 0
right = right * 2 + 2
for i in range(left, right + 1):
labels[i - leaf_min_index] = tree_labels[old_index]
return {'features': features, 'labels': labels}
result_str = ''
for i in range(10):
res = get_leaf_labels(rf.estimators_[i].tree_, 10)
for j in range(len(res['labels'])):
result_str += "assign label_{}[{}] = 10'b".format(i, j)
for k in range(10):
if 9 - k == res['labels'][j]:
result_str += '1'
else:
result_str += '0'
result_str += ";\n"
for i in range(10):
res = get_leaf_labels(rf.estimators_[i].tree_, 10)
for j in range(len(res['features'])):
result_str += "assign feature_index_{}[{}] = 10'd{};\n".format(i, j, res['features'][j])
print(result_str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment