Reputation: 333
I am doing classification. I have two arrays, the first is 'Actual', and the second is 'Predicted'. I want to compare these two arrays. Suppose the first array is:
Actual = [1, 1, 2, 3, 1]
this tells us that the the first, second, and the last indexes are corresponding to class 1.
The 'Predicted' array is:
Predicted = [1, 1, 1, 3, 3]
this tells us that the first and second indexes have been predicted accurately.
I want the output the tells us just those indexes that accurately predicted as 1, like this:
output = [True, True, False, False, False]
Update I want to evaluate just based on value 1. If you see, the forth predicted value is accurately predicted by 3, but I do not want that, because I want evaluate 1 value.
Upvotes: 3
Views: 8426
Reputation: 52223
Presuming length
of two lists are same:
>>> [(x == y == 1) for x, y in zip(Actual, Predicted)]
[True, True, False, False, False]
To feel safe;
>>> from itertools import izip_longest
>>> [(x == y == 1) for x, y in izip_longest(Actual, Predicted, fillvalue=0)]
[True, True, False, False, False]
Upvotes: 6
Reputation: 95639
First, some array basics:
To get the number of elements in an array, use len
:
x = ['a', 'b', c']
y = len(x) # y == 3
To access the i
th element of an array, use []
:
x = ['a','b', 'c']
y = x[1] # y == 'b'
To obtain an iterator with values 0, 1, ..., n-1 ,use range(n)
:
x = list(range(3)) # x = [0, 1, 2]
To iterate through the values of an array, use for ... in
:
x = ['a', 'b', 'c']
for value in x:
process(value) # called for 'a', 'b', and 'c'
To compare items for equality, use ==
(or !=
for inequality).
Putting this altogether,now:
def ComputeArrayDifference(a, b):
alen = len(a)
blen = len(b)
if alen != blen:
raise DifferingSizesException('Inputs have different sizes', a, b)
result = []
for i in range(alen):
result.append(a[i] == b[i])
return result
Upvotes: 0
Reputation: 91009
If you do not mind using numpy
library, then this can be done very easily -
In [10]: import numpy as np
In [11]: Actual=[1,1,2,3,1]
In [12]: ActualNp = np.array(Actual)
In [13]: Predicted=[1,1,1,3,3]
In [15]: PredictedNp = np.array(Predicted)
In [20]: (ActualNp == PredictedNp) & (PredictedNp == 1)
Out[20]: array([ True, True, False, False, False], dtype=bool)
If not, assumming that you only want to check till the length of the smallest list (If they are of different lengths), you can use zip
-
>>> Actual=[1,1,2,3,1]
>>> Predicted=[1,1,1,3,3]
>>> output = [a == b == 1 for a,b in zip(Actual,Predicted)]
>>> output
[True, True, False, False, False]
Upvotes: 2
Reputation: 895
A one liner simple approach would be
def get_prediction_results(prediction, actual, predicted):
return [a == predicted[i] == prediction for i, a in enumerate(actual)]
>>> get_prediction_results(1, [1,1,2], [1,1,2])
[True, True, False]
Upvotes: 0