tensorflow中的masks()和padding():tf.sign()、tf.reduce_sum()、axis含义、expand_dims()

mask函数生成的具体内部细节方法

tf.sign()

等价于numpy.sign,除了NaN.

sign(
    x,   # 一个tensor或者sparseTensor
    name=None  # 可选
)
返回数字符号的元素指示

如果x < 0,则有 y = sign(x) = -1;如果x == 0,则有 0 或者tf.is_nan(x);如果x > 0,则有1.

# 正整数
tf.sign(121) ---> 1
# 正浮点数
tf.sign(121.1) ---> 1.0

# 负整数
tf.sign(-121) ---> -1
# 负浮点
tf.sign(-121.7) ---> -1.0

对于NaN和0输入返回零.

tf.reduce_sum()

关于reduce_sum()或者求和、求整、求平均等等这样的函数,一定要明白axis的含义,这里的axisnumpy中的mean()有一些不同。
可以粗略的理解为 :

  1. np.mean()axis是几,那就表明哪一维度被压缩成1。
  2. tf.reduce_sum():axis是几,那表明哪一维度被删除掉。
    举例
x = np.random.randn(3,4)
array([[-0.27169034, -1.29395748, -0.83626077, -0.73862962],
       [-0.8269278 , -1.32515378, -0.27239636, -0.49199163],
       [-0.87840893,  0.73217269, -0.59406828,  0.26069466]])
# 测试mean求平均函数
print(np.mean(x, axis=0, keepdims=True))
print(np.mean(x, axis=1, keepdims=True))
[[-0.65900903 -0.62897953 -0.56757514 -0.32330886]] # (1, 4)
[[-0.78513456]    # (3, 1)
 [-0.72911739]
 [-0.11990246]]
# 测试reduce_mean
x_ = tf.convert_to_tensor(x)
sess.run(tf.reduce_sum(x_,axis=0))
# outputs
[ 0.20910891 -3.74189456 -0.5715151   0.97240834]
# 维度(4)
'''
证明了
1. 在`np.mean()`中**axis是几,那就表明哪一维度被压缩成1。**
2. 在`tf.reduce_sum()`:**axis是几,那表明哪一维度被删除掉。**
'''

这样的思想目前适用于所有的情况。

tf.expand_dims()

众所周知的扩展用法,而且只能在边上或者中间进行扩展
例如某个矩阵维度是[2,3,4],只能在0,1,2,3进行扩展。而且扩展位置维度必然是1shape会增加。
例:

# 例1
x.shape # [2,3,4]
tf.expand_dims(x,-1)  # [2,3,4,1]
# 例2
tf.expand_dims(x,1)   # [2,1,3,4]

tf.abs()

众所周知的求绝对值的方法,不管是多少维度,所有元素都变成绝对值。

tf.sign()

众所周知的,啊,不好意思,类似三元选择
tf.sign(x, name=None)作用是:

if x > 0: return 1
elif x < 0 : return -1
elif x = 0 : return 0

tf.title()

扩展,众所周知的扩展,shape不变

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import tensorflow as tf import tensorflow_hub as hub from tensorflow.keras import layers import bert import numpy as np from transformers import BertTokenizer, BertModel # 设置BERT模型的路径和参数 bert_path = "E:\\AAA\\523\\BERT-pytorch-master\\bert1.ckpt" max_seq_length = 128 train_batch_size = 32 learning_rate = 2e-5 num_train_epochs = 3 # 加载BERT模型 def create_model(): input_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name="input_word_ids") input_mask = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name="input_mask") segment_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name="segment_ids") bert_layer = hub.KerasLayer(bert_path, trainable=True) pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids]) output = layers.Dense(1, activation='sigmoid')(pooled_output) model = tf.keras.models.Model(inputs=[input_word_ids, input_mask, segment_ids], outputs=output) return model # 准备数据 def create_input_data(sentences, labels): tokenizer = bert.tokenization.FullTokenizer(vocab_file=bert_path + "trainer/vocab.small", do_lower_case=True) # tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') input_ids = [] input_masks = [] segment_ids = [] for sentence in sentences: tokens = tokenizer.tokenize(sentence) tokens = ["[CLS]"] + tokens + ["[SEP]"] input_id = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_id) segment_id = [0] * len(input_id) padding_length = max_seq_length - len(input_id) input_id += [0] * padding_length input_mask += [0] * padding_length segment_id += [0] * padding_length input_ids.append(input_id) input_masks.append(input_mask) segment_ids.append(segment_id) return np.array(input_ids), np.array(input_masks), np.array(segment_ids), np.array(labels) # 加载训练数据 train_sentences = ["Example sentence 1", "Example sentence 2", ...] train_labels = [0, 1, ...] train_input_ids, train_input_masks, train_segment_ids, train_labels = create_input_data(train_sentences, train_labels) # 构建模型 model = create_model() model.compile(optimizer=tf.keras.optimizers.Adam(lr=learning_rate), loss='binary_crossentropy', metrics=['accuracy']) # 开始微调 model.fit([train_input_ids, train_input_masks, train_segment_ids], train_labels, batch_size=train_batch_size, epochs=num_train_epochs)这段代码有什么问题吗?
最新发布
05-24

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值