How to check if two tensors are equal - tensorflow.js

Given two tensors of any rank, how can I tell if they both are the same, have I to set my propre solution of there is any kind of implementation of this comparaison

To check if two tensors are equal, one can use tf.equal. But it returns a tensor, a result of a bitwise operation. This tensor elements are whether 1 or 0. Therefore computing the sum of the later tensor should give the number of elements of the tensor if both tensors are equal.
const a = tf.tensor([1, 2, 3, 4], [2, 2]);
const b = tf.tensor([1, 2, 3, 4], [2, 2]);
const c = a.equal(b).sum().dataSync()[0]
console.log(c)
c === a.shape.reduce((a,b) => a *= b) ? console.log("true") : console.log("false")
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
</head>
<body>
</body>
</html>

In case somebody needs it for python, the following expression can be used:
tf.math.reduce_all(tf.equal(a,b))

Related

Deleting and adding numpy array rows in a for loop to create a dynamic subarray from larger numpy array,

Summary of problem
Ultimate goal
I would like to take a sub-array from a large input numpy array. This sub array is dynamic, and every iteration through the larger numpy input array will change the sub array so that I can perform a set of calculations that depend on previous iterations of the array. This involves nested for loops, which I realize is not very pythonic, but I don't know of another way.
Problem
The problem arises when I add to the existing dynamic sub-array, it seems to grow extra bracketing. This seems simple to fix, but I am having trouble adapting my Matlab knowledge of array indexing to numpy indexing. I have not even started implementing my calculations yet, but I cannot seem to get the structure of this loop correct.
What I've tried
I have [tried this originally in Pandas][1]. Originally, I thought I could write a pretty simply program to do this using pandas indexing and column naming. But it was SLOW! So I trying to streamline this by
changing the architecture and
relying on numpy instead of Pandas.
Below is a simple program that emulates what I want to do. I am sure I will have other questions, but this is the start. I have a simple (5, 2) array that I loop through the rows of. With each row after row 0, I add the new row to the top of the temp sub-array and delete the last row of the array, maintaining a (2, 2) array throughout. However, as you will see when you run this code, it results in some strange behavior that results in not being able to write the results into the output array. You will also see that I have tried several ways to add and delete columns. Whether these are optimal is besides the point - the current code is the closest I have gotten to running this program!
Some Example code
This code 'works' in the sense that it doesn't trow errors. However, it doesnt' produce the desired results. In this case it would be an output array with the same values as the inputs (because I am not doing any calculations- this is just to get the architecture correct). The desired result would be that each loop creates a sub array in this order:
n=1 [1 1]
n=2 [[1,1], [2,2]]
n=3 [[2, 2], [3, 3]]
n=4 [[3, 3], [4, 4]]
...
N [[N-1, N-1], [N, N]].
This does not need to be limited to 2 items (if list) or rows (if array), and the length will be set by an input variable. Thus, the size of this array must be dynamic (set during the call of the function). Furthermore, I supply a simple example here, but each loop will basically need to add a row from the input. It will be a little more advanced than simply a 2 member NDarray. Lists have the advantage of being able to use .append and .pop attributes, but as far as I can tell, arrays do not. I present the following code example using only arrays.
import numpy as np
a = np.array([[1, 1], [2, 2], [3, 3], [4,4], [5,5]])
print('Original a array: ', a)
out = np.empty_like(a)
b = np.empty(len(a[0,:]))
for ii, rr in enumerate(a):
if ii == 0:
c = [a[ii]]
else:
print('Before: ', c)
#Add next row from array a to the temp array for calculations
c = np.insert(c, 1, [rr], axis=0)
print('During: ', c)
#Remove the last row of the temp array prior to calculations
#indices_to_remove = [0]
#d = c[~np.isin(np.arange(c.size), [indices_to_remove])]
d = c[1::]
c = [d]
print('After: ', c)
#Add the temp array to the output array after calculations
#THIS THROWS ERRORS, AND I THINK IT IS DUE TO THE INCREASING NUMBERS OF BRACKETS.
#out[ii, :] = c
#print(c)
[1]: https://stackoverflow.com/questions/70186681/nested-loops-altering-rows-in-pandas-avoiding-a-value-is-trying-to-be-set-on?noredirect=1#comment124076103_70186681
MATLAB is 1-base indexing whereas Python uses 0-base indexing.
let's say we have a 2D array like this:
a= [[1, 2],
[3, 4],
[5, 6]]
In MATLAB if you do a(1, 1) you will get 1 in python a[1, 1] you will get 4. Also as you know in MATLAB you can do natural indexing which works if you do a(6) = 6 in python if you do that you will get IndexError: . it is almost the same, except in python it starts from 0.
Here is the working example with your desired results.
import numpy as np
a = np.array([[1, 1], [2, 2], [3, 3], [4,4], [5,5]])
test = []
for idx in range(len(a)):
if idx == 0:
test.append(a[idx])
test.append(a[idx:idx+2, :])
# remove the last [5, 5]
test.pop(-1)
for i in test:
print(i, end=',\n')
output
[1 1],
[[1 1]
[2 2]],
[[2 2]
[3 3]],
[[3 3]
[4 4]],
[[4 4]
[5 5]],

Two if statements in a for loop?

class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
x=arr
while True:
f=True
for i in range(1,len(arr)-1):
if arr[i-1]<arr[i] and arr[i]>arr[i+1]:
f=False
x[i]=x[i]-1
print(x[i])
if arr[i-1]>arr[i] and arr[i]<arr[i+1]:
f=False
x[i]=x[i]+1
print(x[i])
#print(x)
x=arr
if f==True:
break
return x
In the above code both the if statements don't execute , only the second one does. I have tried using elif but it still doesn't work. What am i missing here?
For your code, I considered two types of examples as input for the array list
For example 1, when the arr = [1, 2, 1, 4], the 2nd element is bigger than 1st and 3rd
The first if statement (if arr[i-1]<arr[i] and arr[i]>arr[i+1]:) is working, because both the conditions are met and it gives the output x = [1, 1, 1, 4]
In example 2, when the arr = [3, 2, 3, 4], the 2nd element is smaller than the 1st and 3rd
The second if statement (if arr[i-1]>arr[i] and arr[i]<arr[i+1]:) is working, because both the conditions are met and it gives the output x = [3, 3, 3, 4]
So, the working of if statements largely depends on the elements in the array. Both the if statements' purpose is totally opposite. If one satisfies the condition the other will not.
Hope my answer provides some clarification.

Tensorflow JS Probabilties

i have multiple feature columns and a result column where i want to predict if something happens or not.
so I'm training my model and finally i do
const predictions = model.predict(xTest).argMax(-1);
this returns a tensor and when getting the data with:
predictions.dataSync ()
i get values like [0, 1, 1, 1, 0, ...]
is there any way to get probabilities like in python? [0.121, 0.421, 0.8621, ...]
I only found one result:
https://groups.google.com/a/tensorflow.org/g/tfjs/c/TvcB69MUj_I?pli=1
is this still the case? are there no probabilities in javascript?
tf.argMax returns the indices of the maximum value along the axis. If you rather want to have the maximum value itself you could use tf.max instead
const x = tf.tensor2d([[1, 2, 3],[ 4, 8, 4]]);
x.max(-1).print() // [3, 8]
x.argMax(-1).print() // [2, 1]

Difference between two arrays in Angular JS

Consider following arrays:
array1 = ['a','b'];
array2 = ['a','b','c','d'];
I need to extract the difference. So my resulting array should look something like,
array3 = ['c','d'];
If an element is present in array1 then it should be poped from array2.
I am looking for solutions more angular way,is there any directive available?
In my opinion you can use underscore or lodash library for such tasks.
for example in underscore you can done it through this simple code :
difference_.difference(array, *others)
Similar to without, but returns the values from array that are not present in the other arrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
underscore annotated source

Concatenating an array of arrays in Coffeescript

I'm trying to find an elegant way in Coffeescript to merge an array of arrays, so that [[1,2,3],[4,5,6],[7,8,9]] ==> [1,2,3,4,5,6,7,8,9].
As you might imagine, I need this because I'm generating arrays from a function in a "for in" construct and need to concatenate the resulting nested array:
result = (generate_array(x) for x in arr)
Is there an elegant way to handle this? Thanks for any pointers!
Just use the JS idiom:
[].concat.apply([], a)
which becomes a little nicer in Coffee:
$ coffee -e 'a = [[1,2,3],[4,5,6],[7,8,9]]; console.dir [].concat a...'
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
OK, one way is to include the underscore.js library. It is a very nice, lightweight but powerful utility library, and it has _.flatten which does exactly this.
Barring that, you could take the underscore.js code for flatten and modify it to remove any other underscore dependencies to create your own standalone "flatten".
Here's the underscore.js "_.flatten" code:
_.flatten = function(array) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
Notice that it is doing some nice stuff for you. For example, many of the underscore functions like _.reduce will check to see if the browser has implemented a native version, which some have. If so, it will use the native which of course runs much faster. The _.isArray implementation does the same thing.
What about this for Coffee
[[1, 2, 3], [4, 5, 6], [7, 8, 9]].reduce (a, b) ->
a.concat b
or this for pure Javascript
[[1, 2, 3], [4, 5, 6], [7 , 8, 9]].reduce((a, b) => a.concat(b));
sugarjs is another elegance way to do it:
[[1, 2, 3]].flatten() //=> [1, 2, 3]
sugarjs: flatten
Why not try using Lodash?
_.flatten([1,2,3], [4,5,6]) => [1,2,3,4,5,6]
https://lodash.com/docs#flatten

Resources