python - 什么是 X_train 和 y_train?

标签 python machine-learning logistic-regression

我想开始使用机器学习开发应用程序。我想对文本进行分类 - 垃圾邮件或非垃圾邮件。我有 2 个文件 - spam.txtham.txt - 每个文件包含数千个句子。如果我想使用分类器,比如说 LogisticRegression

例如,正如我在网上看到的那样,为了适合我的模型,我需要这样做:

`lr = LogisticRegression()
model = lr.fit(X_train, y_train)`

那么我的问题来了,X_trainy_train 到底是什么?我怎样才能从我的句子中得到它们?我在互联网上搜索,我不明白,这是我最后一次打电话,我对这个话题很陌生。谢谢!

最佳答案

根据文档(参见 here):

  • X 对应于形状为 (n_samples, n_features) 的 float 特征矩阵(也就是训练集的设计矩阵)
  • y 是形状为 (n_samples,) 的浮点目标向量(标签向量)。在您的情况下,标签 0 可能对应于垃圾邮件示例,而 1 对应于垃圾邮件示例

The question is now about how to get a float feature matrix from text data.

一个常见的方案是使用 tf-idf 矢量化(更多关于 here ),它在 sklearn 中可用。 .

矢量化可以通过 Pipeline 与逻辑回归链接起来sklearn 的 API。

代码大概是这样的

from itertools import chain

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression

import numpy as np

# prepare string data
with open('spam.txt', 'r') as f:
   spam = f.readlines()

with open('ham.txt', 'r') as f:
   ham = f.readlines()

text_train = list(chain(spam, ham))

# prepare labels
labels_train = np.concatenate((np.zeros(len(spam)),np.ones(len(ham))))

# build pipeline
vectorizer = TfidfVectorizer()
regressor = LogisticRegression()

pipeline = Pipeline([('vectorizer', vectorizer), ('regressor', regressor)])

# fit pipeline
pipeline.fit(text_train, labels_train)

# test predict
test = ["Is this spam or ham?"]
pipeline.predict(test) # value in [0,1] 

关于python - 什么是 X_train 和 y_train?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662425/

相关文章:

python - 将 python 字符串从列表打印到 gui

python - 请求.exceptions.SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

python - 使用多个分隔符拆分字符串,并保留*一些*分隔符,但不是全部

python - 将一列中的数组值转换为原始 DataFrame 的列的最佳方法是什么?

python - Matplotlib - 在 x 轴上隐藏特定刻度

javascript - 如何计算神经网络的输出?

python - 如何分割社交图(矩阵形式)?

python - Tensorflow 下一个词预测器错误

python - 控制 Scikit Learn 中逻辑回归的阈值

java - 如何使用java在spark mllib中获取逻辑回归的p值