有没有办法训练 ML 模型来将单词分类?
Is there a way to train an ML model to classify words into categories?
我希望训练一个 ML 模型来将单词分为几大类,在我的例子中是:颜色。所以我会有一些预定义的颜色桶,例如:
let blue = ["blue", "royal", "dark blue", "light blue"]
let red = ["red", "cardinal", "dusty red", "red polka dot"]
我想要
a) 模型对桶中已经存在的颜色进行分类,即如果给定 "blue" 它将知道 "blue" 在 blue
桶中。
b) 模型采用以前未见过的词,例如 "faded blue",并将它们分类到正确的桶中,在本例中 blue
基于某种置信度分数.
我不确定这是否可行,我目前使用的方法是一系列用于分类的 if 语句,但我想知道是否有更直观的方法使用 ML 来执行此操作型号。
你可以试试 scikit-learn:
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
data = {'blue': ["blue", "royal", "dark blue", "light blue"],
'red': ["red", "cardinal", "dusty red", "red polka dot"]}
train_data = pd.DataFrame(data).T.reset_index()
train_data.rename(columns={'index':'target'}, inplace=True)
# predictors
X = train_data.drop('target', axis=1)
X = X.apply(lambda x: ','.join(x), axis=1)
# target
y = train_data.target
# simple toy model
clf = Pipeline(steps=[
('vec', CountVectorizer(ngram_range=(1, 2),)),
('clf', LogisticRegression())
])
# train a model
clf.fit(X,y)
# predict a new value
print(clf.predict(['faded blue']))
希望这会让您走上正确的道路:)
以上结果:
我希望训练一个 ML 模型来将单词分为几大类,在我的例子中是:颜色。所以我会有一些预定义的颜色桶,例如:
let blue = ["blue", "royal", "dark blue", "light blue"]
let red = ["red", "cardinal", "dusty red", "red polka dot"]
我想要
a) 模型对桶中已经存在的颜色进行分类,即如果给定 "blue" 它将知道 "blue" 在 blue
桶中。
b) 模型采用以前未见过的词,例如 "faded blue",并将它们分类到正确的桶中,在本例中 blue
基于某种置信度分数.
我不确定这是否可行,我目前使用的方法是一系列用于分类的 if 语句,但我想知道是否有更直观的方法使用 ML 来执行此操作型号。
你可以试试 scikit-learn:
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
data = {'blue': ["blue", "royal", "dark blue", "light blue"],
'red': ["red", "cardinal", "dusty red", "red polka dot"]}
train_data = pd.DataFrame(data).T.reset_index()
train_data.rename(columns={'index':'target'}, inplace=True)
# predictors
X = train_data.drop('target', axis=1)
X = X.apply(lambda x: ','.join(x), axis=1)
# target
y = train_data.target
# simple toy model
clf = Pipeline(steps=[
('vec', CountVectorizer(ngram_range=(1, 2),)),
('clf', LogisticRegression())
])
# train a model
clf.fit(X,y)
# predict a new value
print(clf.predict(['faded blue']))
希望这会让您走上正确的道路:)
以上结果: