You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP-ML持久化功能使用问题:模型恢复后预测报错

解决PHP-ML模型恢复后预测时的"Missing feature"错误

问题原因

你遇到的错误核心是只保存了训练好的NaiveBayes分类器,却没有保存用于特征转换的TokenCountVectorizer。训练阶段,Vectorizer会根据训练数据生成固定的词汇表(对应模型的特征集合),分类器正是基于这个固定维度的特征完成训练的。但恢复模型时,你没有加载这个训练好的Vectorizer,后续预测时要么Vectorizer未初始化,要么使用了全新的、未经过训练的Vectorizer,导致转换后的新句子特征向量维度和分类器预期的不一致,从而触发特征数量不匹配的错误。

解决方案

需要将Vectorizer和分类器一起保存,恢复时同时加载两者,确保预测时使用的是和训练阶段完全一致的特征转换规则。

修改后的代码示例

require_once __DIR__ . '/vendor/autoload.php';

use Phpml\Classification\NaiveBayes;
use Phpml\FeatureExtraction\TokenCountVectorizer;
use Phpml\Tokenization\WhitespaceTokenizer;
use Phpml\ModelManager;

$modelPath = '/var/www/ai/models/sentiment_analyzer';
$vectorizerPath = '/var/www/ai/models/vectorizer'; // 新增Vectorizer的保存路径
$modelManager = new ModelManager();

if (!file_exists($modelPath) || !file_exists($vectorizerPath)) {
    // 训练数据
    $sentences = [
       'I love this product!',
       'This is terrible, do not buy it.',
       'The customer service was amazing.',
       'I am very disappointed with this purchase.',
       'The quality of this item is excellent.',
       'I would recommend this to anyone.',
       'This product is a waste of money.',
       'The shipping was fast and efficient.',
       'I regret buying this product.',
       'This is the best product I have ever used.'
    ];
    
    $labels = [
       'positive',
       'negative',
       'positive',
       'negative',
       'positive',
       'positive',
       'negative',
       'positive',
       'negative',
       'positive'
    ];

    // 初始化并训练Vectorizer
    $vectorizer = new TokenCountVectorizer(new WhitespaceTokenizer());
    $vectorizer->fit($sentences);
    $vectorizedSentences = $vectorizer->transform($sentences);

    // 用转换后的特征向量训练分类器
    $classifier = new NaiveBayes();
    $classifier->train($vectorizedSentences, $labels);

    // 同时保存分类器和Vectorizer
    $modelManager->saveToFile($classifier, $modelPath);
    $modelManager->saveToFile($vectorizer, $vectorizerPath);
} else {
    // 同时加载分类器和训练好的Vectorizer
    $classifier = $modelManager->restoreFromFile($modelPath);
    $vectorizer = $modelManager->restoreFromFile($vectorizerPath);
}

// 预测新句子的情感
$newSentence = 'This product is not worth the money.';
$newSentenceVector = $vectorizer->transform([$newSentence])[0];
$predictedLabel = $classifier->predict($newSentenceVector);

echo 'Prediction : ' . $predictedLabel;

额外注意事项

  • 训练时必须使用transform返回的特征向量去训练分类器,原代码中直接用原句子数组训练是不规范的(虽然transform会修改原数组,但显式使用返回值更清晰)。
  • 要保证保存的Vectorizer和分类器一一对应,不能混用不同训练批次的文件,否则仍会出现特征维度不匹配的问题。

内容的提问来源于stack exchange,提问作者user21208635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:45:35