复现TensorFlow版本MAE的shuffle和reshuffle

在encoder的输入需要非masked token,然后decoder的输入需要把对应位置的token用0代替进去,只想解决这个接口,所以解决目标就是按指定位置先取出对应的token,省略中间处理步骤,在按照index位置把非masked token塞回原大小矩阵。

废了2个小时,菜狗终于解决了这个问题(丢)

写了个小测试代码

import tensorflow as tf
import numpy as np
#值矩阵
target_tensor = tf.constant([[7, 2], [9, 6], [1, 3]])
#假装mask
mask_tensor2 = tf.constant([[1, 0], [0, 0], [1, 0]])
#把mask矩阵转为bool矩阵
mask = mask_tensor2>0
#为了方便直接flatten了
index = tf.where(tf.reshape(~mask,[-1]))
#为了对比结果用的
masked_tensor2 = tf.boolean_mask(target_tensor, ~mask)
#塞回去,为了省事没有reshape,直接在flatten上复原了
mm = tf.sparse_tensor_to_dense(tf.SparseTensor(indices=index, values=masked_tensor2, dense_shape=[6]))

输出结果如图示

参考链接

https://www.jianshu.com/p/831cc6f5d810

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是基于TensorFlow的欠拟合和过拟合的Python示例: 首先,我们需要导入必要的库和数据集: ```python import tensorflow as tf from tensorflow import keras import numpy as np # 加载数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.boston_housing.load_data(seed=42) ``` 接下来,我们需要对数据进行预处理: ```python # 标准化数据 mean = x_train.mean(axis=0) std = x_train.std(axis=0) x_train = (x_train - mean) / std x_test = (x_test - mean) / std ``` 然后,我们可以定义一个函数来构建模型: ```python def build_model(): model = keras.Sequential([ keras.layers.Dense(64, activation='relu', input_shape=(x_train.shape[1],)), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(1) ]) optimizer = tf.keras.optimizers.RMSprop(0.001) model.compile(loss='mse', optimizer=optimizer, metrics=['mae']) return model ``` 接下来,我们可以训练模型并绘制训练和验证的损失曲线: ```python # 构建模型 model = build_model() # 训练模型 history = model.fit(x_train, y_train, epochs=500, validation_split=0.2, verbose=0) # 绘制训练和验证的损失曲线 import matplotlib.pyplot as plt def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Abs Error [$1000]') plt.plot(history.epoch, np.array(history.history['mae']), label='Train Loss') plt.plot(history.epoch, np.array(history.history['val_mae']), label = 'Val loss') plt.legend() plt.ylim([0,5]) plt.show() plot_history(history) ``` 最后,我们可以使用测试集评估模型的性能: ```python # 使用测试集评估模型的性能 test_loss, test_mae = model.evaluate(x_test, y_test, verbose=0) print('Test MAE: ${:,.2f}'.format(test_mae * 1000)) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值