javascript - 有没有办法在 javascript 中使用 keras.pad_sequences?
问题描述
@keras_export('keras.preprocessing.sequence.pad_sequences')
def pad_sequences(sequences, maxlen=None, dtype='int32',
padding='pre', truncating='pre', value=0.):
return sequence.pad_sequences(
sequences, maxlen=maxlen, dtype=dtype,
padding=padding, truncating=truncating, value=value)
我想将此代码转换为 javascript。
它是这样工作的:
sequence = [[1], [2, 3], [4, 5, 6]]
tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=2)
array =
0,1
2,3
5,6
解决方案
您可以使用 Javascript 截断和填充序列,如下所示:
const sequence = [[1], [2, 3], [4, 5, 6]];
var new_sequence = sequence.map(function(e) {
const max_length = 2;
const row_length = e.length
if (row_length > max_length){ // truncate
return e.slice(row_length - max_length, row_length)
}
else if (row_length < max_length){ // pad
return Array(max_length - row_length).fill(0).concat(e);
}
return e;
});
console.log('Before truncating and paddig: ',sequence)
console.log('After truncating and paddig: ', new_sequence)
// "Before truncating and paddig: ", [[1], [2, 3], [4, 5, 6]]
// "After truncating and paddig: ", [[0, 1], [2, 3], [5, 6]]
这等效于以下带有 Tensorflow 的 Python 代码:
import tensorflow as tf
def truncate_and_pad(row):
row_length = tf.shape(row)[0]
if tf.greater(row_length, max_length): # truncate
return row[row_length-max_length:]
elif tf.less(row_length, max_length): # pad
padding = tf.constant([[max_length-row_length.numpy(), 0]])
return tf.pad(row, padding, "CONSTANT")
else: return row
max_length = 2
sequence = tf.ragged.constant([[1], [2, 3], [4, 5, 6]])
Y = tf.map_fn(truncate_and_pad, sequence)
但您实际上不需要任何花哨的功能。
推荐阅读
- nginx - 在端口 80 和 443 上没有连接到 Nginx docker 容器
- javascript - 为什么我的函数不断添加 DOM 节点?
- url-rewriting - IIS 重写全局规则仅适用于默认文档
- javascript - Angular 材质 sidenav 项目在单击后保持焦点
- sql - Postgres Query 根据两个不同的行选择值
- java - FileNotFoundException - 拒绝访问
- python-3.x - Py2app 找不到模块
- sql - 具有多个属性且数据库表不多的产品数据库
- c++ - 用唯一的 int 填充数组
- python - 对字典中的字典列表进行排序