Tensorflow基本用法

因需求需要用到些Tensorflow的知识,所以简单入门一下
首先我们去安装tensorflow,tensorflow有CPU版本和GPU版本有关tensorflow的安装可以看这个视频,讲解的很好tensorflow2.0的安装
安装好后我们进行代码操作

import tensorflow as tf

a = tf.constant(2.5)   # 定义一个常量,给a赋值为2.5
print(a)

b = tf.Variable(10, name="var")    #  定义一个变量,初始值10,名字为var
print(b)

在这里插入图片描述
分别定义了一个常亮和一个变量,但是打印出来确实类型的解释,tensorflow的数据都要放到session会话中执行

import tensorflow.compat.v1 as tf   #  如果是tensorflow2.0这么写     而 tensorflow 1.x写作 import tensorflow as tf
tf.disable_v2_behavior()     #  表示继续使用1.x版本的语法


a = tf.constant(2.5)   # 定义一个常量,给a赋值为2.5
print(a)

b = tf.Variable(10, name="var")    #  定义一个变量,初始值10,名字为var
print(b)

sess = tf.Session()    #创建session会话   
print(sess.run(a))

sess.close()   # 关闭session

在这里插入图片描述
可以看到打印了2.5
我们也可以给他指定数据类型如下

a = tf.constant(2, dtype=tf.int32)

但是我们打印这个变量b却是报错的,那是因为变量在tensorflow中都要进行初始化

init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(b))

在这里插入图片描述
我们也可以用with as来创建session

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(3.4)
b = tf.Variable(12)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(a))
    print(sess.run(b))
tensorflow四则运算

常量的计算

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(8)
b = tf.constant(2)

x1 = tf.add(a, b)
x2 = tf.multiply(a, b)
x3 = tf.subtract(a, b)
x4 = tf.divide(a, b)

with tf.Session() as sess:
    print(sess.run(x1))
    print(sess.run(x2))
    print(sess.run(x3))
    print(sess.run(x4))

在这里插入图片描述

变量的运算

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(8)
b = tf.Variable(2)
init = tf.global_variables_initializer()

x1 = tf.add(a, b)
x2 = tf.multiply(a, b)
x3 = tf.subtract(a, b)
x4 = tf.divide(a, b)

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(x1))
    print(sess.run(x2))
    print(sess.run(x3))
    print(sess.run(x4))

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值