TensorFlowNotes
TensorFlow
load tensorflow.js first and then read Core Concepts
load tensorflow
==========
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.5"></script>
create tensors
==========
// create a vector: sampleVec = tf.tensor([1,3,7,9])
// create a matrix or a higher dimensional tensor: tf.tensor([[1, 2], [3, 4]]);
// create a matrix with a flat array and a shape: tf.tensor([1, 2, 3, 4], [2, 2]);
// to enhance code readability, use: tf.scalar, tf.tensor1d, tf.tensor2d, tf.tensor3d and tf.tensor4d.
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
// Open the browser devtools to see the output
model.predict(tf.tensor2d([5], [1, 1])).print();
});
some tensor ops
===================
square:
=======
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]]
add:
====
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]]
chainable of ops:
=================
const sq_sum = e.add(f).square();
sq_sum.print();
// Output: [[36 , 64 ],
// [100, 144]]
const sq_sum = tf.square(tf.add(e, f));
model
===================
a model is a function
two ways to create models, use ops directly to represent the work the model does.
For example:
// Define function
function predict(input) {
// y = a * x ^ 2 + b * x + c
return tf.tidy(() => {
const x = tf.scalar(input);
const ax2 = a.mul(x.square());
const bx = b.mul(x);
const y = ax2.add(bx).add(c);
return y;
});
}
// Define constants: y = 2x^2 + 4x + 8
const a = tf.scalar(2);
const b = tf.scalar(4);
const c = tf.scalar(8);
// Predict output for input of 2
const result = predict(2);
result.print() // Output: 24
the other way is to use the tf.model to construct a model out of layers, which are a popular abstraction in deep learning.
The following code constructs a tf.sequential model:
const model = tf.sequential();
model.add(
tf.layers.simpleRNN({
units: 20,
recurrentInitializer: 'GlorotNormal',
inputShape: [80, 4]
})
);
const optimizer = tf.train.sgd(LEARNING_RATE);
model.compile({optimizer, loss: 'categoricalCrossentropy'});
model.fit({x: data, y: labels});
There are many different types of layers available in TensorFlow.js.
A few examples include tf.layers.simpleRNN, tf.layers.gru, and tf.layers.lstm.
http://qt.gtimg.cn/q=
==========
http://qt.gtimg.cn/q=
http://qt.gtimg.cn/r=2&q=r_hk01072
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.6.1';
document.head.appendChild(script);
$.getScript('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.6.1');
$.getScript('http://qt.gtimg.cn/r=2&q=r_hk01072"');
v_r_hk01072
string.split(separator, limit)
jsonp colllect external file
==========
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$(document).ready(function(){
}
s.src = "http://qt.gtimg.cn/r=2&q=r_hk01072?callback=myDisplayFunction";
document.body.appendChild(s);
//$("head").append(script);
//document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
$("button").click(function(){
$.get("http://qt.gtimg.cn/r=2&q=r_hk01072", function(data, status){
console.log(data);
alert("Data: " + data + "\nStatus: " + status);
});
});
$("button").click(function(){
$.get("http://qt.gtimg.cn/r=2&q=r_hk01072", function(data, status){
console.log(typeof(data));
});
});
================
This works!
$(document).ready(function(){
$.get("http://qt.gtimg.cn/r=2&q=r_hk01072", function(data, status){console.log(data);})
});
================
linear regression
==========
const m = tf.variable(tf.scalar(Math.random())) // slope
const b = tf.variable(tf.scalar(Math.random())) // y intercept
const predict = x =>
tf.tidy(() => {
const xVector = tf.tensor1d(x); // Create a vector of x values
const yPred = xVector.mul(this.m).add(this.b); // y = mx + b
return yPred
})
const loss = (yPred, y) => yPred.sub(y).square().mean(); // loss function: mean squared error
const learningRate = 0.5;
const optimizer = tf.train.sgd(learningRate); // optimiser: stochastic gradient descent
// train function: running ~60 times per second
const train = () => {
tf.tidy(() => {
if (x_vals.length > 0) {
const y = tf.tensor1d(y_vals)
optimiser.minimize(() => loss(predict(x_vals), y)); // auto adjusts tf.variable coefficents
}
})
}
// getting values from tensors is async
predict([-1, 1]).data().then(yVals => {
two.makeLine( // plot the Two.js line on the canvas
// x1, y1
-1 * width, height * yVals[0]),
// x2, y2
1 * width, height * yVals[1]
})
linear regression sample
==========
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"></script>
<script>
const m = tf.variable(tf.scalar(Math.random())) // slope
const b = tf.variable(tf.scalar(Math.random())) // y intercept
function predict(x) {
return tf.tidy(function() { return m.mul(x).add(b);});
}
function loss(prediction, actualValues) { return prediction.sub(actualValues).square().mean();}
const learningRate = 0.01;
const optimizer = tf.train.sgd(learningRate);
function train() {
optimizer.minimize(function() {
const predsYs = predict(tf.tensor1d(trainX));
return loss(predsYs, tf.tensor1d(trainY))
});
}
theStepLoss = 10
while (if theStepLoss > 0.1) {
theStepLoss = train();
}
</script>
data.gtimg
==========
hkHSI
http://data.gtimg.cn/flashdata/hk/minute/hkHSI.js?maxage=10
0930-1600 minute data
weekly data
http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_weekqfq¶m=hk00060,week,,,320,qfq
This is monthly data!!
http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_monthqfq¶m=hkHSI,month,,,320,qfq
This is Five day data!!
http://web.ifzq.gtimg.cn/appstock/app/day/query?_var=fdays_data_hkHSI&code=hkHSI
kline_day 320
http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_dayqfq¶m=hkHSI,day,,,320,qfq
kline_day 30
http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_dayqfq¶m=hkHSI,day,,,30,qfq
RGraph.AJAX.getJSON(url, callback)
=====================
theurl = 'http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_dayqfq¶m=hkHSI,day,,,320,qfq'
RGraph.AJAX.getJSON(theurl, function (json){newjson = json});
var keys = Object.keys(newjson); // read the structure
newjson.data.hkHSI.day[320][0] // date
newjson.data.hkHSI.day[320][1] // open
["2018-08-22", "27836.678", "27844.932", "27919.299", "27579.801", "77596553908", {…}, "0", "7759655.391"]
date, o c h l v v
}