温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TensorFlow基础中的常量是什么

发布时间:2021-12-10 10:44:42 来源:亿速云 阅读:143 作者:柒染 栏目:大数据

TensorFlow基础中的常量是什么,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

下面介绍TensorFlow中与常量相关的几个函数:

  • tf.constant #常量张量

  • tf.convert_to_tensor  #转换成张量

  • tf.range  #整数等差

  • tf.linspace  #线性等分

  • tf.random.uniform   # 均匀分布

  • tf.random.normal  #正态分布

示范1:

import numpy as np
import tensorflow as tf

g = tf.Graph()
with g.as_default():

    #  tf.constant可以创建一个常量张量
    a = tf.constant([1,2,3],dtype = tf.int32)

    # tf.convert_to_tensor有类似作用
    # 可以将Python列表或者numpy数组转换成常量张量
    b = tf.convert_to_tensor([1,2,3], preferred_dtype =tf.float32)

with tf.Session(graph = g) as sess:
    print(sess.run({'a':a,'b':b}))

输出结果如下:

TensorFlow基础中的常量是什么

示范2:

import tensorflow as tf

g = tf.Graph()
with g.as_default():

    # tf.range 创建整数等差数列
    # 使用语法为tf.range(start, limit=None, delta=1)
    c = tf.range(1,12,2)

    # tf.linspace 为线性等分函数,创建浮点数等差数列
    # 使用语法为tf.linspace(start, stop, num)
    d = tf.linspace(0.0,1.0,9)

with tf.Session(graph = g) as sess:
    print(sess.run({'c':c}))
    print(sess.run({'d':d}))

输出结果如下:

TensorFlow基础中的常量是什么

示范3:

import tensorflow as tf

g = tf.Graph()
with g.as_default():

    # tf.random.uniform创建元素值均匀分布的张量
    u = tf.random.uniform(shape=[3,3],minval=0,maxval=5,dtype=tf.int32)

    # tf.random.normal创建元素值正态分布的张量
    v = tf.random.normal(shape=[6],mean= 0.0,stddev=1.0,dtype=tf.float32)

with tf.Session(graph = g) as sess:
    print('u=\n',sess.run(u))
    print('v=\n',sess.run(v))

输出结果如下:

TensorFlow基础中的常量是什么

此外,有许多与numpy中类似的函数也可以用来创建常量张量。

例如 tf.zeros,tf.ones,tf.zeros_like,tf.diag ...

看完上述内容,你们掌握TensorFlow基础中的常量是什么的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI