如何给Rubix ML TextNormalizer的transform()传参?解决传参报错
问题分析与解决方案
核心问题拆解
- 按引用传参错误:Rubix ML的
TextNormalizer::transform()方法参数为按引用传递,不能直接传入临时数组(如[$text]),必须传入可被引用的变量。 - 样本格式错误:Rubix ML的转换器要求样本为二维数组结构——每个样本是包含特征的子数组,即使单特征也要嵌套一层,而非一维数组或单独字符串。
- transform()返回值误解:Rubix ML转换器的
transform()方法是原地修改输入数组,返回值为null,不能通过赋值接收结果。
修正后的完整代码
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Rubix\ML\Datasets\Labeled; use Rubix\ML\Extractors\CSV; use Rubix\ML\Transformers\TextNormalizer; use Rubix\ML\Transformers\WordCountVectorizer; use Rubix\ML\Transformers\TfIdfTransformer; use Rubix\ML\Persisters\Filesystem; use Rubix\ML\Classifiers\KNearestNeighbors; use Rubix\ML\CrossValidation\Reports\MulticlassBreakdown; use Rubix\ML\CrossValidation\Reports\ConfusionMatrix; use Log; class PredictorCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:predictor'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Execute the console command. * * @return int */ public function handle() { echo "Please enter your text: "; $inputText = readline(); $prediction = $this->predict($inputText); echo "Prediction: {$prediction}"; return Command::SUCCESS; } public function predict($inputText) { // Load the trained model $modelPath = '/var/www/gdpr/tests/model.rbx'; $modelData = file_get_contents($modelPath); $estimator = unserialize($modelData); // 初始化转换器 $textNormalizer = new TextNormalizer(); $wordCountVectorizer = new WordCountVectorizer(10000); $tfIdfTransformer = new TfIdfTransformer(); // 构建符合Rubix ML要求的二维样本数组 $samples = [[$inputText]]; // 原地执行转换(transform无返回值,直接修改原数组) $textNormalizer->transform($samples); $wordCountVectorizer->fit($samples)->transform($samples); $tfIdfTransformer->fit($samples)->transform($samples); // 执行预测 $prediction = $estimator->predictSample($samples[0]); return $prediction; } }
关键修正说明
- 样本结构调整:将输入文本包装为
[[ $inputText ]],符合Rubix ML对“样本-特征”二维结构的要求。 - 引用传递处理:将样本存入变量
$samples后再传入transform(),避免临时数组无法被引用的问题。 - 移除错误赋值:直接调用
transform()修改原数组,不再尝试接收其返回的null值。 - 优化handle方法:无需重新实例化
PredictorCommand,直接使用$this->predict()调用方法。
内容的提问来源于stack exchange,提问作者Inigo EC
相关产品推荐
相关产品推荐

