Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
for (let row in this.trainData) {
let val = this.trainData[row]
if (val.target + "" === 1 + "") {
if (trainEcg.length < this.state.trainDataSize) {
trainEcg.push(val)
} else {
break
}
}
}
// console.log(maxAbnormalCount, "abnormal samples", abnormalCount, "Total", trainEcg.length);
// Create train tensor from json array
this.xsTrain = tf.tensor2d(trainEcg.map(item => item.data
), [trainEcg.length, trainEcg[0].data.length])
this.setState({ trainDataShape: this.xsTrain.shape })
// Create test data TENSOR from test data json array
let testData = this.testData.slice(0, this.state.testDataSize)
this.xsTest = tf.tensor2d(testData.map(item => item.data
), [testData.length, testData[0].data.length])
// Create yLabel Tensor
this.yTest = testData.map(item => item.target + "" === 1 + "" ? 0 : 1)
this.setState({ testDataShape: this.xsTest.shape })
}
// const input = tf.tensor2d(sequence, [1, 13000]);
log('starting...');
// const input = tf.tensor2d(sequence);
// const paddedSequence = padSequences([sequence], 13000);
// log('paddedSequence', paddedSequence);
// sequence.forEach(index => paddedSequence[index] = 1);
// log('ones', _.flatMap(paddedSequence, (val, i) => val === 1 ? [i] : []));
const paddedSequence = _.range(0, 13000).map(index => {
return (sequence.indexOf(index) !== -1) ? 1 : 0;
});
log('ones', _.flatMap(paddedSequence, (val, i) => val === 1 ? [i] : []));
// do prediction
const input = tf.tensor2d(paddedSequence, [1, 13000]);
log('input', input);
const prediction = model.predict(input);
log('prediction', prediction);
const score = prediction.dataSync()[0];
log('score', score);
prediction.dispose();
return score;
} catch(err) {
console.error('caught');
console.error(err);
return null;
}
}
const actualBatchLength = batchLength + 2 * RF_PAD;
const firstBatch =
tf.tensor2d(input.slice(0, actualBatchLength)).expandDims(0) as
tf.Tensor3D;
const lastBatch = tf.tensor2d(input.slice(input.length - actualBatchLength))
.expandDims(0) as tf.Tensor3D;
if (batchSize === 2) {
return tf.concat([firstBatch, lastBatch], 0);
}
// Add zero padding to make the length divisible by the
// this.batchLength. Don't worry about receptive field padding for now.
let naivePaddedBatches;
if (batchRemainder) {
naivePaddedBatches = tf.tensor2d(input)
.pad([[0, batchLength - batchRemainder], [0, 0]])
.as3D(batchSize, batchLength, -1);
} else {
naivePaddedBatches =
tf.tensor2d(input.slice(0, input.length - mergedRemainder))
.as3D(batchSize, batchLength, -1);
}
// Slice out the receptive field padding we will need for all but the
// first and last batch.
const leftPad = tf.slice(
naivePaddedBatches, [0, batchLength - RF_PAD], [batchSize - 2, -1]);
const rightPad = tf.slice(naivePaddedBatches, [2, 0], [-1, RF_PAD]);
// Pad the middle (not first and last) to cover the receptive field.
const midBatches = tf.concat(
[leftPad, naivePaddedBatches.slice(1, batchSize - 2), rightPad], 1);
const tf = require('@tensorflow/tfjs');
// Load the binding:
// 这里可以解锁cpu性能,不安装的话命令行会有一行提示,但这个包需要翻墙,可能对初学者会有一些困难
// 安装了的话,直接解除注释即可使用
// require('@tensorflow/tfjs-node');
// 这里可以解锁gpu性能,和上面一致,不多说,电脑性能好的,可以二选一使用
// Use '@tensorflow/tfjs-node-gpu' if running with GPU.
const d = tf.tensor2d([[1.0, 2.0], [3.0, 4.0]]);
const d_squared = d.square();
d_squared.print();
// Output: [[1, 4 ],
// [9, 16]]
const e = tf.tensor2d([[1.0, 2.0], [3.0, 4.0]]);
const f = tf.tensor2d([[5.0, 6.0], [7.0, 8.0]]);
const e_plus_f = e.add(f);
e_plus_f.print();
// Output: [[6 , 8 ],
// [10, 12]]
.expandDims(0) as tf.Tensor3D;
if (batchSize === 2) {
return tf.concat([firstBatch, lastBatch], 0);
}
// Add zero padding to make the length divisible by the
// this.batchLength. Don't worry about receptive field padding for now.
let naivePaddedBatches;
if (batchRemainder) {
naivePaddedBatches = tf.tensor2d(input)
.pad([[0, batchLength - batchRemainder], [0, 0]])
.as3D(batchSize, batchLength, -1);
} else {
naivePaddedBatches =
tf.tensor2d(input.slice(0, input.length - mergedRemainder))
.as3D(batchSize, batchLength, -1);
}
// Slice out the receptive field padding we will need for all but the
// first and last batch.
const leftPad = tf.slice(
naivePaddedBatches, [0, batchLength - RF_PAD], [batchSize - 2, -1]);
const rightPad = tf.slice(naivePaddedBatches, [2, 0], [-1, RF_PAD]);
// Pad the middle (not first and last) to cover the receptive field.
const midBatches = tf.concat(
[leftPad, naivePaddedBatches.slice(1, batchSize - 2), rightPad], 1);
return tf.concat([firstBatch, midBatches, lastBatch], 0);
}
tf.tidy(() => {
// Prepare input data as a 2D `tf.Tensor`.
const inputData = ui.getManualInputData();
const input = tf.tensor2d([inputData], [1, 4]);
// Call `model.predict` to get the prediction output as probabilities for
// the Iris flower categories.
const predictOut = model.predict(input);
const logits = Array.from(predictOut.dataSync());
const winner = data.IRIS_CLASSES[predictOut.argMax(-1).dataSync()[0]];
ui.setManualInputWinnerMessage(winner);
ui.renderLogitsForManualInput(logits);
});
}
private calculateMultiVariateCoeff(X, y): number[] {
const [q, r] = tf.linalg.qr(tf.tensor2d(X));
const rawR = reshape(Array.from(r.dataSync()), r.shape);
const validatedR = validateMatrix2D(rawR);
const weights = tf
.tensor(numeric.inv(validatedR))
.dot(q.transpose())
.dot(tf.tensor(y))
.dataSync();
return Array.from(weights);
}
}
getTrainData() {
const xs = tf.tensor4d(
this.trainImages,
[this.trainImages.length / IMAGE_SIZE, IMAGE_H, IMAGE_W, 1]);
const labels = tf.tensor2d(
this.trainLabels, [this.trainLabels.length / NUM_CLASSES, NUM_CLASSES]);
return {xs, labels};
}
xPowerStddevs.push(xPowerStddev);
const normalizedXPower = normalizeVector(xPower, xPowerMean, xPowerStddev);
normalizedXPowers.push(normalizedXPower);
}
const xArrayData = [];
for (let i = 0; i < xData.length; ++i) {
for (let j = 0; j < order + 1; ++j) {
if (j === 0) {
xArrayData.push(1);
} else {
xArrayData.push(normalizedXPowers[j - 1][i]);
}
}
}
return [
xPowerMeans, xPowerStddevs, tf.tensor2d(xArrayData, [batchSize, order + 1]),
yMean, yStddev, tf.tensor2d(yNormalized, [batchSize, 1])
];
}
const momentStack = classCategories.map((category: T) => {
const classFeatures: tf.Tensor = tf.tensor2d(
separatedByCategory[category.toString()] as number[][],
null,
'float32',
) as tf.Tensor;
return tf.moments(classFeatures, [0]);
});