TensorFlow.js入门:一维向量的学习

转载自:https://blog.csdn.net/weixin_34061042/article/details/89700664

一维向量及其运算

tensor 是 TensorFlow.js 的数据中心单元:由一组数值组成的一维或多维数组。在 TensorFlow.js中,一维向量的构造函数主要为:tf.tensor()和tf.tensor1d()

可以用set()和get()函数分别获取和设置向量中的元素值。
  一维向量的运算函数有很多,说明如下:

  • tf.add() 两个向量的对应元素的和
  • tf.sub() 两个向量的对应元素的差
  • tf.mul() 两个向量的对应元素的乘积
  • tf.div() 两个向量的对应元素的商
  • tf.maximum() 两个向量的对应元素的最大值
  • tf.minimum() 两个向量的对应元素的最小值
  • tf.pow() 两个向量的对应元素的幂

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

简单例子

我们通过一个小小的例子,来说明在TensorFlow.js中一维向量的使用方法。

<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>
        a = [1,2,3,4,5];
        b = [2,3,4,5,6];
        function show(){
            const vector1 = tf.tensor(a);
            const vector2 = tf.tensor(b);
            const res = vector2.add(vector1);       
            document.getElementById("first_element").innerHTML = "第一个元素为" + res.get(0)+ ".";
            document.getElementById("whole_array").innerHTML = "向量:"+res;
        }   
    </script>
</head>
<body>
  <script type="text/javascript">
      function printa()
      {
          document.write("a: " + a + "<br>");
      }
      function printb()
      {
          document.write("b: " + b + "<br>");
      }
      printa();
      printb();
  </script>
  <p id="first_element"></p>
  <p id="whole_array"></p>
  <button onclick="show()" id="show" value="show">show</button>
</body>
</html>
View Code

接下来,我们实现稍微复杂的功能,进行张量的其他运算

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

<body>
    <center>
    <h2>TensorFlow向量(一维)学习</h2>
    <br><br>
    <div style="600px">
        
        <div>
            <label class="col-sm-2 control-label">向量运算</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">显示结果</button>
            <button class="btn btn-default" id="clc">清空</button>
            </div>
        </div>
    
    </div>
    
    <table class="table" style="600px">
        <caption id="tf">运行结果</caption>
        <tbody>
            <tr class="success" id="table">
            </tr>
        </tbody>
    </table>
    
    </center>
</body>
</html>
一维向量运算演示.html
$(document).ready(function(){
    
    var flag; 
    /*
    flag = 1表示一元运算
    flag = 2表示二元运算
    */
    
    // 清空两个输入框的输入
    $("#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的运算函数,输出计算结果
    $("#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("输入的两个向量长度不一样");
        }
        
        // 利用tensorflow.js的运算函数
        if( flag == 1 || ((flag == 2) && (vector1.length == vector2.length))){
            var op = $("input[name='optionsRadiosinline']:checked").val();
            const pow2 = tf.tensor(2).toInt(); // 计算平方
            const pow3 = tf.tensor(3).toInt(); // 计算三次方
        
            switch (op) // JavaScript的switch结构
            {
                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":  // 两个向量中的最大值,element-wise
                    res = tf.tensor(vector1).maximum(tf.tensor(vector2));
                    break;
                case "min":  // 两个向量中的最小值,element-wise
                    res = tf.tensor(vector1).minimum(tf.tensor(vector2));
                    break;
                case "abs":  // 绝对值
                    res = tf.tensor(vector1).abs();
                    break;
                case "sin":  // 正弦函数
                    res = tf.tensor(vector1).sin();
                    break;
                case "cos":  // 余弦函数
                    res = tf.tensor(vector1).cos();
                    break;
                case "tan":  // 正切函数
                    res = tf.tensor(vector1).tan();
                    break;
                case "exp":  // 指数函数,以e为底
                    res = tf.tensor(vector1).exp();
                    break;
                case "log":  // 对数函数,以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(""); // 清空原有表格中的数据
            // 输入计算结果
            for(var i=0; i< res.shape; i++){
                $("tr").append("<td>"+res.get(i)+"</td>;");
            }
        }
        
    });
    
});
calculate.js

效果如下:

全部的代码可见:github 

原文地址:https://www.cnblogs.com/lfri/p/11850829.html