当前位置:网站首页>tensorflow使用笔记
tensorflow使用笔记
2022-04-22 07:08:00 【海滩上的那乌克丽丽】
张量:
张量是一个多维数组,与numpy ndarray相似
有一维张量、二维张量,三维张量等等
张量创建
在构建的时候整形默认是int32,浮点型默认是float32
import tensorflow as tf
import numpy as np
# 创建0维张量
print(tf.constant(3))
# tf.Tensor(3, shape=(), dtype=int32)
# 创建一维张量
print(tf.constant([1, 2, 3]))
# tf.Tensor([1 2 3], shape=(3,), dtype=int32)
# 创建二维张量
print(tf.constant([[1, 2],[3, 4]]))
"""
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
"""
# 创建三维张量
print(tf.constant([
[[1, 2],
[3, 4]],
[[4, 5],
[6, 7]]
]))
"""
tf.Tensor(
[[[1 2]
[3 4]]
[[4 5]
[6 7]]], shape=(2, 2, 2), dtype=int32)
"""
如何理解三维数组?
[3, 2, 5]
可以理解为三个两行五列的数组拼接在一起。

张量转换成numpy
# 将张量转换成numpy
tensor1 = tf.constant([1, 2, 3, 4, 5])
print(np.array(tensor1))
print(tensor1.numpy())
张量运算
# 张量运算常用函数
a = tf.constant([[1, 2],
[3, 4]])
b = tf.constant([[1, 2],
[1, 1]])
# 加法
print(tf.add(a, b))
"""
[[2 4]
[4 5]], shape=(2, 2), dtype=int32)
"""
# 乘法
print(tf.multiply(a, b))
"""
[[1 4]
[3 4]], shape=(2, 2), dtype=int32)
"""
# 矩阵乘法
print(tf.matmul(a, b))
"""
[[ 3 4]
[ 7 10]], shape=(2, 2), dtype=int32)
"""
张量常用聚合函数
# 最大值
print(tf.reduce_max(a))
# tf.Tensor(4, shape=(), dtype=int32)
tf.reduce_mean
tf.reduce_sum
tf.reduce_min
# 最大值索引
print(tf.argmax(a))
# tf.Tensor([1 1], shape=(2,), dtype=int64)
变量:是一种特殊的参数,形状是不可改变的,但是其中的参数可以改变
var = tf.Variable([[1, 2], [3, 4]])
print(var.shape())
# 改变参数前先变成numpy数组
var.numpy()
# 改变其中参数,但是不能改变他的形状
print(var.assign([[4, 5], [6, 7]]))
对于tensorflow1.0版本来说是构建了静态图
前面定义好了,后面要用tf.Session()才能出结果
import tensorflow as tf
print(tf.__version__)
x = tf.Variable(3, name='x')
y = tf.Variable(4, name='y')
f = x*x*y + 2
print(f)
sess= tf.Session()
# 变量需要初始化(如果前面用的变量Variable,在Session里面一定要初始化)
sess.run(x.initializer)
sess.run(y.initializer)
result = sess.run(f)
print(result)
sess.close()
with tf.Session() as sess:
x.initializer.run()
y.initializer.run()
result = f.evel()
# 全局初始化,不用一个一个的对变量进行初始换,直接用这个全部进行初始化,只需要在Session里面run就可以
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
result = f.eval()
print(result)
默认情况下我们创建的变量会添加到默认的Graph图里面去
有时我们或许想要管理多个独立的图,可以创建一个新的图,并且临时使用with让新创建的变量添加到这个独立的Graph中。
graph1 = tf.Graph()
x3 = tf.Variable(3)
with graph1.as_default():
x2 =tf.Variable(3) # 添加到了自己创建的graph1中
x4 = tf.Variable(23) # 在with外,没有添加到Graph中
print(x2.graph is graph1) # 查看是否在自己创建的图里面
print(x4.graph is tf.get_default_graph()) # 查看是否在默认的图里面
在深度学习中,我们使用最多的是minGD,那么每批次传入的数据都一样。
所以在tensorflow中,我们一般使用tf.placeholder占位
在Session的时候在传入不同的数据
X = tf.placeholder(dtype=tf.float32)
y = tf.placeholder(dtype=tf.float32)
for i in range(n_batch):
sess.run(training_op, feed_dict={
X: X_train[i*batch_size: i*batch_size + batch_size],
y: y_train[i*batch_size: i*batch_size + batch_size]
})
# shape规定传入的大小,shape=(None, 3)可以是任意行,必须是三列
# 因为我们最后一个批次的数据量有可能较少,所以这里shape第一个维度不固定
A = tf.placeholder(dtype=tf.float32, shape=(None, 3))
B = A + 5
with tf.Session() as sess:
B_val_1 = B.eval(feed_dict={A: [[1, 2, 3]]})
B_val_2 = B.eval(feed_dict={A: [['4', 5, 6],
[7, 8, 9]]})
print(B_val_1)
print(B_val_2)
tensorflow中梯度下降优化器。
这里需要注意一点当我们用优化器的时候,优化器会自动调整前面定义的Variable变量,所以我们在使用优化器的时候,我们一般会将前面的X,y设置成tf.placeholder,而不是Variable变量。
我们会将需要调整的参数theta设置成Variable。
minimize():求导,更新参数

cast:强转。将数据类型强转成float32
tf.cast(correct_prediction, tf.float32)
tf保存模型:
saver = tf.train.Saver()
save_path = saver.save(sess, "./ckpt/my_model_final.ckpt")
tf中计算交叉熵损失函数,这个函数有个sparse(稀疏)所以要求传进来的数据不用做One-hot编码,logits是前面多层网络计算得到的z(没有经过softmax的数值)

这个也是求交叉熵,但是这个没有sparse稀疏, 所以要求传入做好One-hot编码的数值。
不过这个交叉熵是一个总交叉熵,我们需要做一下reduce.mean()求平均,才能得到我们的loss
得到loss后我们就可以进行梯度下降,求最小loss

tf.nn.in_top_k()
版权声明
本文为[海滩上的那乌克丽丽]所创,转载请带上原文链接,感谢
https://blog.csdn.net/h2728677716/article/details/124316146
边栏推荐
- Cherno_游戏引擎系列教程(5):101~
- Differences between routing modes
- 软件测试面试题汇总
- Blocking queue
- tf.keras.layers.Dense函数
- ACM入门之【容斥定理】
- Byte experts jointly create the latest jetpack compose complete set of learning notes, including project practice exercises (with demo)
- 波场TRON创始人孙宇晨宣布将正式上线去中心化稳定币USDD
- Architects evaluate the current situation and development prospect of software industry
- OpenFeign组件的简介和使用
猜你喜欢

OpenFeign组件的简介和使用

ADB advanced commands

16 way E1 optical transceiver + 4-way 100M Ethernet optical transceiver PDH optical transceiver 2m integrated service optical transceiver

STM32对舵机SG90的PWM输出

深度确定性策略梯度(DDPG)

双光口保护8E1+8路物理隔离百兆100M以太网络光端机PDH光端机

Hanyuan hi tech 8-way multi service PDH optical transceiver double optical port protection + 8-way E1 + 4-way Gigabit Ethernet + 4-way 100m network electric port

微信小程序页面路由

opencv将多张图片合成视频

服务雪崩效应
随机推荐
JMeter parameter request type
Redis entry required
光纤传输16路E1+4路千兆隔离以太网络光端机2M专网千兆以太网综合多业务PDH光端机
monkey
JMETER的JDBC配置方法
如何在Win10系统下统计某目录下所有文件的数量
Blocking queue
Hanyuan hi tech 8-way multi service PDH optical transceiver double optical port protection + 8-way E1 + 4-way Gigabit Ethernet + 4-way 100m network electric port
金九银十面试季,字节跳动面试题拿走不谢(附详细答案解析)
Selenium driver installation
汉源高科8E1专网4路百兆隔离网络PDH光端机E1专网业务16M业务光端机
CAS:36530-06-0氯化硼亚酞菁|亚酞菁|氯化硼亚酞菁|二氯硼酞菁染料|氯化亚酞菁硼|BORONSUBPHTHALOCYANINECHLORIDE
软件测试之接口自动化面试题汇总
lnmp mysql 允许远程访问
Wechat applet page routing
SQL 基础(八)数据更新操作实战演练
牛客白月赛5 【题解 数学场】
oh-my-notepro
信息学奥赛一本通 1211:判断元素是否存在 | OpenJudge 1.13 41:判断元素是否存在
MYSQL04_算术、逻辑、位、运算符、运算符对应的习题