Keras--常用函数

import keras.backend as K

1.维度操作

K.permute_dimensions()

K.permute_dimensions(x, pattern)重新排列张量的轴。

  • x: 张量或变量。
  • pattern: 维度索引的元组,例如 (0, 2, 1)

K.reshape()

K.reshape(x, shape)将张量重塑为指定的尺寸。

  • x: 张量或变量。
  • shape: 目标尺寸元组。

K.expand_dims()

K.expand_dims在索引 axis 轴,添加 1 个尺寸的维度。

  • x: 张量或变量。
  • axis: 需要添加新的轴的位置。

K.squeeze()

K.squeeze(x, axis)在索引 axis 轴,移除 1 个尺寸的维度。

  • x: 张量或变量。
  • axis: 需要丢弃的轴。

2.tensor初始化

K.variable()

K.variable(value, dtype=None, name=None, constraint=None)

K.ones()

K.one(2)生成主对角为1的tensor

  • size: Tuple 包含行和列

K.arange()

K.arange(start, end)生成一个1D的tensor,tensor默认的类型为int32

  • start:开始值,start默认0
  • end:结束值,当只传入一个值则为end
  • 一个小技巧生成一个2D的tensorK.arange(10)[None]生成2Dtensorarray([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
    示例
pid = K.arange(20)  # (20, )
print(K.int_shape(pid))
pid = K.expand_dims(pid, 0)  # (1,20)
print(K.int_shape(pid))

(20,)
(1, 20)

3.tensor操作

K.tile()

K.tile(x, n)根据n扩充x

  • x: tesor
  • n: list,n的长度与x的维度数相同
pid = K.tile(K.eye(2), [2, 3])

[[1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1.]]

K.gather()

K.gather(reference, indices)

  • 将indices中的索引替换为reference的向量,所以返回的结果相比于indices会增加一个维度
  • K.gather()调用tf.nn.embedding_lookup(reference, indices)

示例:

emb = K.variable([[1,1,1],[2,2,2],[3,3,3],[4,4,4]])
indices = K.arange(3)[None]
K.eval(K.gather(emb, indices))

array([[[1., 1., 1.],
        [2., 2., 2.],
        [3., 3., 3.]]], dtype=float32)

K.round()

参数:输入一个tensor
K.round()调用tf.round(),tf.round()并不是四舍五入,而是"四舍六入五取偶"

x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5, -5.5, 1.6, 3.5])
with tf.Session() as sess:
    print(sess.run(tf.round(x)))

[ 1.  2.  2.  2. -4. -6.  2.  4.]

tf.round() K.round() 四舍六入五取偶

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值