Printing the value of argMax index? - tensorflow.js

I would like to print the actual value of the argMax index (the highest probability) in this scenario:
const result = await model.predict(t4d);
result.print(); // puts out: Tensor [[0.9899636, 0.0100364],]
result.as1D().argMax().print(); // prints either 0 or 1
Besides the index, I would want to print the actual value 0,XXXX behind argMax(). Any advice for this?
Test that doesn't work:
const confidence = result.dataSync<'float32'()>;
console.log(confidence);
Sorry if this is a question that has been answered any times, I have spent a few hours searching!

The value of the argMax index can be retrieved after getting the data of the tensors
const result = await model.predict(t4d);
const index = await result.as1D().argMax().data()[0]
const predict = await result.data()
// get the value
const value = result[index]
The other possibility would be to use topk
const topk = result.as1D().topk()
// get the highest value
value = topk.value() // the value here is a tensor

Related

Google Apps Script - Randomizing Dropdown - Selecting Index

What I have seems simple, but looking through SO and other sites hasn't let me figure it out.
H3 and S3 are cells with a dropdown data validation list.
I have a button to randomize my these. This is easy when it's a number, but these are strings.
S3 is the cell for size so I have this randomized.
var randSize = Math.floor(Math.random() * (20 - 1 + 1)) + 1
ss.getRange("S3").setValue(randSize)
I don't understand how to either set a random int to select the value based on array index. Or get a random string value based on the entries in cell H3, then setting H3 to equal the new string.
Name | #
random item | random #
I need a random item to be set randomly from a value from H3.
Issue and solution:
If I understand you correctly, you have a set of string values in a column, and you want to copy a random value from that column to the cell H3.
If that's correct, you can just do the following:
Retrieve the column values to a simple array via getValues() and flat.
Retrieve a random value from that array, using length and Math.
Set that value to your target cell, using setValue.
Code sample:
function getRandomValue() {
const ss = SpreadsheetApp.getActiveSpreadsheet(); // If standalone, use openById/openByUrl
const sourceSheet = ss.getSheetByName("COLUMN_VALUES_SHEET_NAME");
const targetSheet = ss.getSheetByName("H3_SHEET_NAME");
const COLUMN_INDEX = 3; // Change according to your preferences
const FIRST_ROW = 2; // Change according to your preferences
const NUM_ROWS = sourceSheet.getLastRow() - FIRST_ROW + 1;
const array = sourceSheet.getRange(FIRST_ROW, COLUMN_INDEX, NUM_ROWS).getValues().flat();
const randomIndex = Math.floor(Math.random() * array.length);
const randomValue = array[randomIndex];
targetSheet.getRange("H3").setValue(randomValue);
}

For Loop is not working as expected when checking array content in last column

I saved the information of this table in an 2D array using Google Apps Script. The whole array building process worked as aspected.
Area
X
Y
Major
Minor
Angle
SensorNo
1
25049
380.500
246.500
190.953
167.023
0
1
2
24248
393.500
247.000
192.976
159.986
0
2
3
18250
382.500
247.000
159.023
146.121
0
3
However, as I tried to build a for loop (as seen in the following code) that goes through every column of the first row of the array I did not get the expected output. I tried to tell the loop that when the array content equals "SensorNo" to save the respective n as a new variable and then break the loop. But whenever the array content I'm looking for is in the last column the variable remains undefined...
for(n=0;n<fileContentArray[0].length;n++){
if(fileContentArray[0][n]=="SensorNo"){
var sensorNoCol=n;
break;
}
}
I hope someone can help me.
Best, Max
function getHeaderColumns() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet Name");
const hRow = 1;
const hA = sh.getRange(hRow, 1, 1, sh.getLastColumn()).getValues()[0];
let col = {};
hA.forEach((h, i) => { col[h] = i + 1 });
return col['SensorNo'];
}

Google AppScript - How to skip certain columns[INDEXes] when setting values from an ARRAY

I am new to coding.
I am trying to edit and set values from an entire row but want to skip certain columns, because there are formulas in it.
In short: I want to / have to keep track of sing-in and sign-out times, which then will be calculated in the spreadsheet but shouldn't be overwritten by the array. Is there a way to skip every 3rd "value"/index (as these are the columns which have the formulas)?
In fact I want to skip the columns: TOTAL, day1tot, day2tot, day3tot .... day14tot.
function editCustomerByID(id,customerInfo){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("DATA");
const custIds = ws.getRange(2, 1, ws.getLastRow()-1, 1).getDisplayValues().map(r => r[0].toString().toLowerCase());
const posIndex = custIds.indexOf(id.toString().toLowerCase());
const rowNumber = posIndex === -1 ? 0 : posIndex +2;
Logger.log(customerInfo);
ws.getRange(rowNumber, 2, 1, 8).setValues([[
customerInfo.name,
customerInfo.total,
customerInfo.day1in,
customerInfo.day1out,
customerInfo.day1tot,
customerInfo.day2in,
customerInfo.day2out,
customerInfo.day2tot
// UNTIL DAY 14
]]);
return true;
To skip columns, you can subdivide your range into individual ranges and implement conditional statements
Sample:
function editCustomerByID(id,customerInfo){
...
var valueArray = [
customerInfo.name,
customerInfo.total,
customerInfo.day1in,
customerInfo.day1out,
customerInfo.day1tot,
customerInfo.day2in,
customerInfo.day2out,
customerInfo.day2tot
// UNTIL DAY 14
]
var startColumn = 2;
//loop through all values
for (var i = 0; i < valueArray; i++){
// filter out every 3rd value
if((i+1) % 3 != 0){
ws.getRange(rowNumber, (startColumn + i)).setValue(valueArray[i]);
}
}
return true;
Note that the sample code above uses the method setValue() instead of setValues()
Performing multiple requests to set values to individual ranges is less efficient that setting all values at once within a single request, however in your case it is necessary since your desired value range is not continuos

How to get an array of object from firestore in appscript

I have a set of documents in Firestore in this format. Questions array will 10 questions.
I want to get the data of questions field: one row for one question
I do I code in the appscript to perform this
This is my code so far (for one document only)
function test(){
const firestore = getFirestore();
var query = firestore.getDocument("QuestionCollection/test").fields;
var data = {};
data.subject = query.subject;
data.questions= query.questions;
const sheet = SpreadsheetApp.getActiveSheet();
for(i = 0 ; i < 10 (no. of question); i++){
const row = [data.questions[i].answer, data.questions[i].difficulty];
sheet.appendRow(row);
}
}
Error:
TypeError: Cannot read property 'answer' of undefined
Modification points:
When I saw your sample data in the image, it seems that the array length of questions is 2. But at the for loop, the end index of loop is 9. I think that by them, such error occurs.
When you want to put the value of "Serial", it is required to add the value for putting to Spreadsheet.
In your script, appendRow is used in a loop. In this case, the process cost becomes high.
When above points are reflected to your script, it becomes as follows.
Modified script:
Your for loop is modified as follows.
From:
for(i = 0 ; i < 10 (no. of question); i++){
const row = [data.questions[i].answer, data.questions[i].difficulty];
sheet.appendRow(row);
}
To:
var values = [];
for (var i = 0; i < data.questions.length; i++) {
const row = [i + 1, data.questions[i].answer, data.questions[i].difficulty];
values.push(row);
}
sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
For the end index of loop, the array length is used.
Reference:
setValues(values)
You shouldn't query the .fields property directly (because your data isn't converted properly). Assuming you're using v28+ of the library, your code should look something like this:
function test(){
const firestore = getFirestore();
const query = firestore.getDocument("QuestionCollection/test").obj; // Don't use .fields here
const sheet = SpreadsheetApp.getActiveSheet();
const values = [["Serial", "Answer", "Difficulty"]]; // Init 2D array with Header row
// Loop through each question in the array and extract necessary values to construct Data rows
for (const question of query.questions){
values.push([query.questions.indexOf(question) + 1, question.answer, question.difficulty]);
}
// Replace 1, 1 below with coords of "Serial" header cell
const range = sheet.getRange(1, 1, values.length, values[0].length);
range.setValues(values);
// sheet.getRange(subjRow, subjCol).setValue(query.subject); // Add location for Subject data
}
I saw that you wanted "Serial" to represent "Question number", so I added that column to the header and data rows.
As Tanaike mentioned, there's a huge performance hit for writing to the spreadsheet in a loop, so it's better if you set up a 2D array of values to write all at once using range.setValues(array2D). Ideally, you'll want to minimize the calls to the Spreadsheet API.
Disclaimer: I'm an active contributor to the FirestoreGoogleAppsScript library.

How to Multiply Each element of an array multiply by each element of Next array in Swift?

I had two Arrays.
let quntityArr = ["1","3","4","7"]
let priceArr = ["£129.95", "£179.95","£169.95","£199.85"]
I want to multiply these both Arrays in the following way
let totalArr = ["1*£129.95", "3*£179.95", "4*£169.95", "7*£199.85"]
Here I want to calculate each price with those product quantities.
You need
let quntityArr:[Double] = [1,3,4,7]
let priceArr = [129.95, 179.95,169.95,199.85]
let totalArr = zip(quntityArr, priceArr).map { "£\($0 * $1)" }
print(totalArr)
Assuming your input data is provided as array of String.
1. Input Data
let quntityArr = ["1","3","4","7"]
let priceArr = ["£129.95", "£179.95","£169.95","£199.85"]
2. Convert input data in array of Int and Double
let quantities = quntityArr
.compactMap(Int.init)
let prices = priceArr
.map { $0.dropFirst() }
.compactMap (Double.init)
3. Verify no input value has been discarded
assert(quntityArr.count == quantities.count)
assert(priceArr.count == prices.count)
4. Do the math
let results = zip(quantities, prices).map { Double($0) * $1 }.map { "£\($0)"}
5. Result
["£129.95", "£539.8499999999999", "£679.8", "£1398.95"]

Resources