Home > Net >  How to write for loop so that y_pr>=1 assign label 1 and y_pr<=-1 assign label -1?
How to write for loop so that y_pr>=1 assign label 1 and y_pr<=-1 assign label -1?

Time:11-04

Given weights w=[8, 10] (1 by 2 vector) and b=-5 for a hyperplane w^Tx b=0 and I want to use this hyperplane to classify the testing dataset X_te (51 by 2). For a data point x_i, the classification is based on if w^Tx_i b >= 1 then assigns the label y=1 and if w^Tx_i b <= -1 then assign the label y=-1.

I try the following code:

def cla(X,w,b):
    pre_te=np.zeros(len(X))
    length=X.shape[0]

    for i in range(length):
        y_pred=np.dot(np.array(X[i]),w.T) b
        if y_pred>=1:
            pre_te[i]=1
        else:
            pre_te[i]=-1
    return pre_te

I can assign 1 to y_pred if y_pred>=1. How to add -1 to y_pred if y_pred<=-1 in the above for loop?

I do not think that write else: pre_te[i]=-1 work... There will be 0 in the output...

CodePudding user response:

I think you need elif

for i in range(length):
        y_pred=np.dot(np.array(X[i]),w.T) b
        if y_pred>=1:
            pre_te[i]=1
        elif y_pred<=-1:
            pre_te[i]=-1
    return pre_te
  • Related