TensorFlow.js入門(一)一維向量的學(xué)習(xí)

TensorFlow的介紹

??TensorFlow是谷歌基于DistBelief進(jìn)行研發(fā)的第二代人工智能學(xué)習(xí)系統(tǒng),其命名來源于本身的運(yùn)行原理。Tensor(張量)意味著N維數(shù)組,F(xiàn)low(流)意味著基于數(shù)據(jù)流圖的計(jì)算,TensorFlow為張量從流圖的一端流動(dòng)到另一端計(jì)算過程。TensorFlow是將復(fù)雜的數(shù)據(jù)結(jié)構(gòu)傳輸至人工智能神經(jīng)網(wǎng)中進(jìn)行分析和處理過程的系統(tǒng)。
??TensorFlow是一個(gè)著名的開源的人工智能系統(tǒng),被廣泛應(yīng)用于語音識(shí)別或圖像識(shí)別等多項(xiàng)機(jī)器學(xué)習(xí)和深度學(xué)習(xí)領(lǐng)域。它目前支持的程序語言有: Java, Python, Go, Lua, R, JavaScript, 其中2018年3 月 31 日 ,TensorFlow 宣布增加支持 JavaScript,并推出開源庫 TensorFlow.js 。
??我們將會(huì)介紹在前端開發(fā)中TensorFlow的相關(guān)內(nèi)容,即TensorFlow.js的學(xué)習(xí)與應(yīng)用。

Tensorflow中的一維向量及其運(yùn)算

??tensor 是 TensorFlow.js 的數(shù)據(jù)中心單元:由一組數(shù)值組成的一維或多維數(shù)組。在 TensorFlow.js中,一維向量的構(gòu)造函數(shù)主要為:tf.tensor()和tf.tensor1d(),具體的API文檔可以參考:https://js.tensorflow.org/api/0.12.0/ 。
??可以用set()和get()函數(shù)分別獲取和設(shè)置向量中的元素值。
??一維向量的運(yùn)算函數(shù)有很多,說明如下:

  • tf.add() 兩個(gè)向量的對(duì)應(yīng)元素的和
  • tf.sub() 兩個(gè)向量的對(duì)應(yīng)元素的差
  • tf.mul() 兩個(gè)向量的對(duì)應(yīng)元素的乘積
  • tf.div() 兩個(gè)向量的對(duì)應(yīng)元素的商
  • tf.maximum() 兩個(gè)向量的對(duì)應(yīng)元素的最大值
  • tf.minimum() 兩個(gè)向量的對(duì)應(yīng)元素的最小值
  • tf.pow() 兩個(gè)向量的對(duì)應(yīng)元素的冪

以上只是一部分,還有更多的函數(shù)如: tf.abs(), tf.sin(), tf.cos(), tf.tan(), tf.tan()等。

簡(jiǎn)單例子

??在網(wǎng)頁中引入TensorFlow.js需要添加“script”標(biāo)簽,如下:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>

??我們通過一個(gè)小小的例子,來說明在TensorFlow.js中一維向量的使用方法,其完整的HTML代碼如下:

<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
    <!-- Place your code in the script tag below.-->
    <script>
        function show(){
            var a = [1,2,3,4,5];
            var b = [2,3,4,5,6];
            const vector1 = tf.tensor(a);
            const vector2 = tf.tensor(b);
            const res = vector2.add(vector1);
            document.getElementById("first_element").innerHTML = "第一個(gè)元素為" + res.get(0)+ ".";
            document.getElementById("whole_array").innerHTML = "向量:"+res;
        }   
    </script>
    
  </head>

  <body>
  <p id="first_element"></p>
  <p id="whole_array"></p>
  <button onclick="show()" id="show" value="show">show</button>
  </body>
  
</html>

顯示的網(wǎng)頁如下圖:

實(shí)戰(zhàn)

??在剛才的例子中,我們僅僅只給出了一個(gè)簡(jiǎn)單的例子,那么,如果要實(shí)現(xiàn)稍微復(fù)雜一點(diǎn)的功能呢,比如下面的網(wǎng)頁:

??我們可以用TensorFlow.js來實(shí)現(xiàn)這些向量運(yùn)算。該網(wǎng)頁的完整的HTML代碼如下:

<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
    <link  rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="tf_result.js"></script>
  </head>

<body>
    <center>
    <h2>TensorFlow向量(一維)學(xué)習(xí)</h2>
    <br><br>
    <div style="width:600px">
        
        <div>
            <label class="col-sm-2 control-label">向量運(yùn)算</label>
            <div class="col-sm-10">
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="add" checked="checked"> 加
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline"  value="sub"> 減
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="mul"> 乘
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="div"> 除
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="max"> max
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="min"> min
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="abs"> abs
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="sin"> sin
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="cos"> cos
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="tan"> tan
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="exp"> exp
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="log"> log
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="sqrt"> sqrt
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="square"> square
                </label>
                <label class="radio-inline">
                <input type="radio" name="optionsRadiosinline" value="cubic"> cubic
                </label>
                <br><br>
            </div>
        </div>
        
        <div>
            <label for="vector1" class="col-sm-2 control-label">向量1</label>
            <div class="col-sm-10">
            <input type="text" class="form-control" id="vector1" placeholder="向量1">
            <br>
            </div>
            
        </div>
        
        <div>
            <label for="vector2" class="col-sm-2 control-label">向量2</label>
            <div class="col-sm-10">
            <input type="text" class="form-control" id="vector2" placeholder="向量2">
            <br>
            </div>
        </div>
        
        <div >
            <div class="col-sm-offset-2 col-sm-10">
            <button class="btn btn-default" id="result">顯示結(jié)果</button>
            <button class="btn btn-default" id="clc">清空</button>
            </div>
        </div>
    
    </div>
    
    <table class="table" style="width:600px">
        <caption id="tf">運(yùn)行結(jié)果</caption>
        <tbody>
            <tr class="success" id="table">
            </tr>
        </tbody>
    </table>
    
    </center>
</body>
</html>

在其中我們用到了tf_result.js,其完整的JavaScript代碼如下:

$(document).ready(function(){
    
    var flag; 
    /*
    flag = 1表示一元運(yùn)算
    flag = 2表示二元運(yùn)算
    */
    
    // 清空兩個(gè)輸入框的輸入
    $("#clc").click(function(){
        $("#vector1").val("");
        $("#vector2").val("");
    });
    
    // 是否允許"向量2"輸入框有輸入
    $("#vector1").click(function(){
        var op = $("input[name='optionsRadiosinline']:checked").val();
        var ops = ["add", "sub", "mul", "div", "max", "min"];
        if (ops.indexOf(op) == -1)
            flag = 1;
        else
            flag = 2;
        
        //文本框"向量2"禁用
        if(flag == 1){
            $("#vector2").val("");
            $("input[type='text']").each(function () {
            $("#vector2").attr("disabled", true);
            });
            
        }
        //文本框"向量2"啟用
        if(flag == 2){
            $("input[type='text']").each(function () {
            $("#vector2").attr("disabled", false);
            });
        }
    });
    
    // 利用tensorflow.js的運(yùn)算函數(shù),輸出計(jì)算結(jié)果
    $("#result").click(function(){
        
        if(flag == 1){
            var vector1 = $("#vector1").val().split(',').map(Number);
        }
        if(flag == 2){
            var vector1 = $("#vector1").val().toString().split(',').map(Number);
            var vector2 = $("#vector2").val().toString().split(',').map(Number);
            if(vector1.length != vector2.length)
                alert("輸入的兩個(gè)向量長(zhǎng)度不一樣");
        }
        
        // 利用tensorflow.js的運(yùn)算函數(shù)
        if( flag == 1 || ((flag == 2) && (vector1.length == vector2.length))){
            var op = $("input[name='optionsRadiosinline']:checked").val();
            const pow2 = tf.tensor(2).toInt(); // 計(jì)算平方
            const pow3 = tf.tensor(3).toInt(); // 計(jì)算三次方
        
            switch (op) // JavaScript的switch結(jié)構(gòu)
            {
                case "add":  // 加法
                    res = tf.tensor(vector1).add(tf.tensor(vector2));
                    break;
                case "sub":  // 減法
                    res = tf.tensor(vector1).sub(tf.tensor(vector2));
                    break;
                case "mul":  // 乘法
                    res = tf.tensor(vector1).mul(tf.tensor(vector2));
                    break;
                case "div":  // 除法
                    res = tf.tensor(vector1).div(tf.tensor(vector2));
                    break;
                case "max":  // 兩個(gè)向量中的最大值,element-wise
                    res = tf.tensor(vector1).maximum(tf.tensor(vector2));
                    break;
                case "min":  // 兩個(gè)向量中的最小值,element-wise
                    res = tf.tensor(vector1).minimum(tf.tensor(vector2));
                    break;
                case "abs":  // 絕對(duì)值
                    res = tf.tensor(vector1).abs();
                    break;
                case "sin":  // 正弦函數(shù)
                    res = tf.tensor(vector1).sin();
                    break;
                case "cos":  // 余弦函數(shù)
                    res = tf.tensor(vector1).cos();
                    break;
                case "tan":  // 正切函數(shù)
                    res = tf.tensor(vector1).tan();
                    break;
                case "exp":  // 指數(shù)函數(shù),以e為底
                    res = tf.tensor(vector1).exp();
                    break;
                case "log":  // 對(duì)數(shù)函數(shù),以e為底
                    res = tf.tensor(vector1).log();
                    break;
                case "sqrt":  // 平方根
                    res = tf.tensor(vector1).sqrt();
                    break;
                case "square":  // 平方
                    res = tf.tensor(vector1).pow(pow2);
                    break;
                case "cubic":  // 三次方
                    res = tf.tensor(vector1).pow(pow3);
                    break;
                default:
                    res = tf.tensor([]);
            }
            
            
            $("#table").html(""); // 清空原有表格中的數(shù)據(jù)
            // 輸入計(jì)算結(jié)果
            for(var i=0; i< res.shape; i++){
                $("tr").append("<td>"+res.get(i)+"</td>;");
            }
        }
        
    });
    
});

??運(yùn)行剛才的網(wǎng)頁,效果如下:


??怎么樣,是不是覺得TensorFlow.js也酷酷的呢?結(jié)合TensorFlow.js以及前端網(wǎng)頁方面的知識(shí),我們可以給出許多酷炫的TensorFlow的應(yīng)用,以后我們會(huì)慢慢講到。本次項(xiàng)目的Github地址為:https://github.com/percent4/tensorflow_js_learning 。

注意:本人現(xiàn)已開通兩個(gè)微信公眾號(hào): 因?yàn)镻ython(微信號(hào)為:python_math)以及輕松學(xué)會(huì)Python爬蟲(微信號(hào)為:easy_web_scrape), 歡迎大家關(guān)注哦~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容