TensorFlow JS:如何用维度不同的X和y训练模型并预测价格
使用firstSequence构造输入预测价格的正确方法
你的核心问题是匹配模型的输入形状要求:模型定义时的inputShape是[7,2](对应单条样本的序列长度+特征数),而预测时需要给模型传入带批量维度的输入(即使只有一条样本)。
现有代码的问题
你当前的输入处理逻辑有误:
const input = tf.tensor(firstSequence)得到的是形状[7,2]的张量,但模型期望的输入格式是[批量数, 7, 2]tf.expandDims(input, 1)会把形状变成[7,1,2],完全不符合模型的输入要求,导致预测结果错误
修正后的输入构造逻辑
只需要给firstSequence添加第0维度(批量维度),让输入形状变成[1,7,2],就能和模型的输入要求匹配:
async function trainAndPredict(priceData, volumeData) { const sequenceLength = 7; const { values:normalizedPrices, min:minPrice, max:maxPrice } = normalizeData(priceData.map(p => p[1])); const { values:normalizedVolumes, min:minVolume, max:maxVolume } = normalizeData(volumeData.map(v => v[1])); const sequences = createSequences(normalizedPrices, normalizedVolumes, sequenceLength); const firstSequence = sequences.shift(); normalizedPrices.splice(-(sequenceLength + 1)); const X = tf.tensor(sequences); const y = tf.tensor(normalizedPrices); console.log("y.shape: "+ y.shape); const model = tf.sequential(); model.add(tf.layers.flatten( { inputShape: [X.shape[1], X.shape[2]] } )); console.log("A2"); model.add(tf.layers.dense({ units: 1 })); model.compile({ optimizer: 'adam', loss: 'meanSquaredError' }); await model.fit(X, y, { epochs: 100 }); // --- 修正的部分开始 --- // 给firstSequence添加批量维度,形状变为[1,7,2] const input = tf.tensor(firstSequence).expandDims(0); // 此时predict返回形状[1,1]的张量 const normalizedPredictedPrice = model.predict(input); // 先把张量转为标量再反归一化 const predictedPrice = denormalizeValue(normalizedPredictedPrice.squeeze(), minPrice, maxPrice); // --- 修正的部分结束 --- return predictedPrice.dataSync()[0]; }
关键说明
expandDims(0):给单条样本添加批量维度,让输入形状从[7,2]变成[1,7,2],完全匹配模型的输入要求squeeze():把模型预测返回的[1,1]张量压缩成标量,确保denormalizeValue能正确处理(如果你的denormalizeValue已经支持张量输入,这一步可以省略)
内容的提问来源于stack exchange,提问作者mtyson
相关产品推荐
相关产品推荐

