我是mlpy库的新手,正在寻找实现句子分类的最佳方法。 我正在考虑使用简单的基本感知器来做它,但从我的理解它是使用预定义的矢量大小但我需要在机器学习时动态增加矢量的大小因为我不想创建一个巨大的矢量(所有英语单词)。 我真正需要做的是获取一个句子列表并从中构建一个分类器向量,然后当应用程序获得新句子时,它会尝试将其自动分类到其中一个标签(监督学习)。
任何想法,想法和例子都会非常有用,
由于
答案 0 :(得分:1)
如果您事先拥有所有句子,则可以准备一份清单 单词(删除停用词)将每个单词映射到一个要素。尺寸 向量的数量将是字典中的单词数。
有一次,你可以训练一个感知器。
看看我的代码,我在其中使用Perl进行映射,然后在matlab中使用perceptron实现,以了解它是如何工作的,并在python中编写类似的实现
准备单词包模型(Perl)
use warnings;
use strict;
my %positions = ();
my $n = 0;
my $spam = -1;
open (INFILE, "q4train.dat");
open (OUTFILE, ">q4train_mod.dat");
while (<INFILE>) {
chomp;
my @values = split(' ', $_);
my %frequencies = ();
for (my $i = 0; $i < scalar(@values); $i = $i+2) {
if ($i==0) {
if ($values[1] eq 'spam') {
$spam = 1;
}
else {
$spam = -1;
}
}
else {
$frequencies{$values[$i]} = $values[$i+1];
if (!exists ($positions{$values[$i]})) {
$n++;
$positions{$values[$i]} = $n;
}
}
}
print OUTFILE $spam." ";
my @keys = sort { $positions{$a} <=> $positions{$b} } keys %positions;
foreach my $word (@keys) {
if (exists ($frequencies{$word})) {
print OUTFILE " ".$positions{$word}.":".$frequencies{$word};
}
}
print OUTFILE "\n";
}
close (INFILE);
close (OUTFILE);
open (INFILE, "q4test.dat");
open (OUTFILE, ">q4test_mod.dat");
while (<INFILE>) {
chomp;
my @values = split(' ', $_);
my %frequencies = ();
for (my $i = 0; $i < scalar(@values); $i = $i+2) {
if ($i==0) {
if ($values[1] eq 'spam') {
$spam = 1;
}
else {
$spam = -1;
}
}
else {
$frequencies{$values[$i]} = $values[$i+1];
if (!exists ($positions{$values[$i]})) {
$n++;
$positions{$values[$i]} = $n;
}
}
}
print OUTFILE $spam." ";
my @keys = sort { $positions{$a} <=> $positions{$b} } keys %positions;
foreach my $word (@keys) {
if (exists ($frequencies{$word})) {
print OUTFILE " ".$positions{$word}.":".$frequencies{$word};
}
}
print OUTFILE "\n";
}
close (INFILE);
close (OUTFILE);
open (OUTFILE, ">wordlist.dat");
my @keys = sort { $positions{$a} <=> $positions{$b} } keys %positions;
foreach my $word (@keys) {
print OUTFILE $word."\n";
}
感知器实施(Matlab)
clc; clear; close all;
[Ytrain, Xtrain] = libsvmread('q4train_mod.dat');
[Ytest, Xtest] = libsvmread('q4test_mod.dat');
mtrain = size(Xtrain,1);
mtest = size(Xtest,1);
n = size(Xtrain,2);
% part a
% learn perceptron
Xtrain_perceptron = [ones(mtrain,1) Xtrain];
Xtest_perceptron = [ones(mtest,1) Xtest];
alpha = 0.1;
%initialize
theta_perceptron = zeros(n+1,1);
trainerror_mag = 100000;
iteration = 0;
%loop
while (trainerror_mag>1000)
iteration = iteration+1;
for i = 1 : mtrain
Ypredict_temp = sign(theta_perceptron'*Xtrain_perceptron(i,:)');
theta_perceptron = theta_perceptron + alpha*(Ytrain(i)-Ypredict_temp)*Xtrain_perceptron(i,:)';
end
Ytrainpredict_perceptron = sign(theta_perceptron'*Xtrain_perceptron')';
trainerror_mag = (Ytrainpredict_perceptron - Ytrain)'*(Ytrainpredict_perceptron - Ytrain)
end
Ytestpredict_perceptron = sign(theta_perceptron'*Xtest_perceptron')';
testerror_mag = (Ytestpredict_perceptron - Ytest)'*(Ytestpredict_perceptron - Ytest)
我不想再次在Python中编写相同的代码,但这应该为您提供如何继续的方向