tensorflow使用笔记

张量:

张量是一个多维数组,与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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值