user2871856
user2871856

Reputation: 227

python simple if else structure wrong comparison

This is my code

for i,val in enumerate(DS3Y_pred_trans):
    if val < 1.5:
        DS3Y_pred_trans[i] = 1
    else:
        DS3Y_pred_trans[i] = 2

There are values less than 1.5 in the list, but the out is all 2s.

What am I missing?

This is the whole code.

from numpy import genfromtxt
DS3X_train = np.genfromtxt('train.csv', dtype=float, delimiter=',')
print DS3X_train

DS3Y_train = np.genfromtxt('train_labels.csv', dtype=int, delimiter=',' )
print DS3Y_train

DS3X_test = np.genfromtxt('test.csv', dtype=float, delimiter=',')
print DS3X_test

DS3Y_test = np.genfromtxt('test_labels.csv', dtype=int, delimiter=',' )
print DS3Y_test

DS3X_train_trans = zip(*DS3X_train)

cov_train = np.cov(DS3X_train_trans)
U, s, V = np.linalg.svd(cov_train, full_matrices=True)
u = U[:,:-1]
u_trans = zip(*u)
DS3X_train_reduced = np.dot(u_trans,DS3X_train_trans) 

b = np.ones((3,2000))
b[1:,:] = DS3X_train_reduced
print "\n"
DS3X_train_reduced = b


DS3X_train_reduced_trans = zip(*DS3X_train_reduced)

temp = np.dot(DS3X_train_reduced,DS3X_train_reduced_trans)

try:
    inv_temp = np.linalg.inv(temp)
except np.linalg.LinAlgError:

    pass
else:

    psue_inv = np.dot(inv_temp,DS3X_train_reduced)
    print psue_inv.shape

weight = np.dot(psue_inv,DS3Y_train)
weight_trans = zip(weight)
print weight_trans



DS3X_test_trans = zip(*DS3X_test)
DS3X_test_reduced = np.dot(u_trans,DS3X_test_trans)

b = np.ones((3,400))
b[1:,:] = DS3X_test_reduced
print "\n"
print b
DS3X_test_reduced = b

print DS3X_test_reduced.shape
DS3X_test_reduced_trans = zip(*DS3X_test_reduced)
DS3Y_pred = np.dot(DS3X_test_reduced_trans,weight_trans)
print DS3Y_pred
print DS3Y_pred.shape 

DS3Y_pred_trans = zip(DS3Y_pred)

print repr(DS3Y_pred_trans[0])

for i,val in enumerate(DS3Y_pred_trans):
    if val < 1.5:
        DS3Y_pred_trans[i] = 1
    else:
        DS3Y_pred_trans[i] = 2


print DS3Y_pred
now regression using indicator variable and graph plottings

Upvotes: 0

Views: 91

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

Your values are not numbers. In Python 2 numbers sort before other objects, so when comparing val with 1.5, the comparison is always false.

You probably have strings:

>>> '1.0' < 1.5
False
>>> 1.0 < 1.5
True

If so, convert your values to floats first:

for i, val in enumerate(DS3Y_pred_trans):
    if float(val) < 1.5:
        DS3Y_pred_trans[i] = 1
    else:
        DS3Y_pred_trans[i] = 2

It could be that you are storing other objects in the list still; you'll need to take a close look at what is actually in the list and adjust your code accordingly, or fix how the list is created in the first place.

Since you are replacing all values anyway, you could use a list comprehension:

DS3Y_pred_trans = [1 if float(val) < 1.5 else 2 for val in DS3Y_pred_trans]

Upvotes: 5

Related Questions