import numpy as np
training_set = np.array([[0, 1, 0, 1, 0, 1],[0, 0, 0, 1, 0, 0],[0, 0, 0, 0, 1, 0],[1, 0, 1, 0, 1, 0],[0, 1, 1, 1, 0, 1],[0, 1, 0, 0, 1, 1],[1, 1, 1, 0, 0, 0],[1, 1, 1, 1, 0, 1],[0, 1, 1, 0, 1, 0],[1, 1, 0, 0, 0, 1],[1, 0, 0, 0, 1, 0]])
def p(X):
Fx = X[:,X.shape[1]-1]
x0= 0
x1= 0
for i in range(len(Fx)):
if Fx[i-1] == 1:
x0 = x0+1
else:
x1 = x1+1
P0 = x0/len(Fx)
P1 = x1/len(Fx)
return(P0,P1)
def H(X):
result = -p(X)[0]*np.log(p(X)[0])-p(X)[1]*np.log(p(X)[1]) #needs to be log2
print("1 = pure, 0 = unpure 1/2 = decision can be random: Calculating Entropy: -" + str(p(X)[0]) + "*" + str(np.log(p(X)[0])) + "-" + str(p(X)[1]) + "*" + str(np.log(p(X)[1])) )
return result
def Q(X,i):
Xi = X[:,i]
result0= 0
result1= 0
for j in range(len(Xi)):
if Xi[j] == 1:
result1 = result1 + len(X[i,:])
else: result0 = result0 + len(X[i,:])
result1 = result1/len(X)
result0 = result0/len(X)
return(result0,result1)
def X_column(X,i,v):
list = X[np.where(X[:,i] == v)]
return list
def IG(X,i):
result = H(X)-Q(X,i)[0]*H(X_column(X,i,0))-Q(X,i)[1]*H(X_column(X,i,1))
return result
#To teach decision trees on learning set S, we will used following alorithm(ID3):
# 1. There is example set S
# 2. If |{f(x) : (x, f(x)) ∈ S}| = 1= 1 create leaf with label f(x)
# 3. For i = 1,2,...,n calculate value IG(S,i)
# 4. May j be an index o fthe biggest of calculated values
# 5. Set node with label Xj
# 6. For subsets:
# S0 = {(x, f(x)) ∈ S : xj = 0}
# and
# S1 = {(x, f(x)) ∈ S : xj = 1}
# run algorithm recurrent (for S ← S0 i S ← S1) and add new nodes as a childs for a node with label j
tree = np.array([])
def ID3(S, recursion = 0):
result = np.array([])
recursion += 1
rows = S.shape[0]
columns = S.shape[1]
if S[:,columns-1].all() == True:
leaf_label = S[0,columns-1]
tree.put(recursion, leaf_label)
return
for i in range(rows):
ig = IG(S,i)
result.put(i, ig)
j = result.max()
leaf_label2 = S[0,j]
tree.put(recursion, leaf_label2)
S0 = X_column(S,i,0)
S1 = X_column(S,i,1)
ID3(S0,recursion+1)
ID3(S1,recursion+2)
return tree
ID3(training_set)
result.put(i, ig) IndexError: index 0 is out of bounds for axis 0 with size 0
Я привык к javascript, поэтому не могу понять, как поместить что-то в массив без предварительной установки размера (я понятия не имею, насколько большим будет дерево решений). Есть ли какие-то функции или есть лучшее решение, о котором я просто не слышал?






Две проблемы, которые я обнаружил до сих пор.
np.put
Повторение ошибки:
li = np.array([])
li.put(0,123) # this gives error as your description
# Correct way of appending
li = np.array([])
li = np.append(li,123)
функция Q (X, i): индекс вне границы
Параметр i - это номер строки X. Он используется в качестве индекса столбца в вашем коде.
def Q(X,i):
Xi = X[:,i] # i is used as a column index.
...