标签: scikit-learn

scikit网格搜索多个分类器

我想知道是否有更好的内置方式来进行网格搜索并在单个管道中测试多个模型.当然,模型的参数会有所不同,这对我来说很复杂.这是我做的:

from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.grid_search import GridSearchCV


def grid_search():
    pipeline1 = Pipeline((
    ('clf', RandomForestClassifier()),
    ('vec2', TfidfTransformer())
    ))

    pipeline2 = Pipeline((
    ('clf', KNeighborsClassifier()),
    ))

    pipeline3 = Pipeline((
    ('clf', SVC()),
    ))

    pipeline4 = Pipeline((
    ('clf', MultinomialNB()),
    ))

    parameters1 = {
    'clf__n_estimators': [10, 20, 30],
    'clf__criterion': ['gini', 'entropy'],
    'clf__max_features': [5, 10, 15],
    'clf__max_depth': ['auto', 'log2', 'sqrt', None]
    }

    parameters2 = {
    'clf__n_neighbors': [3, 7, 10], …
Run Code Online (Sandbox Code Playgroud)

python scikit-learn

26
推荐指数
5
解决办法
1万
查看次数

如何在sklearn中实现前进测试?

在sklearn中,GridSearchCV可以将管道作为参数,通过交叉验证找到最佳估算器.但是,通常的交叉验证是这样的:在此输入图像描述

为了交叉验证时间序列数据,训练和测试数据经常被拆分为:在此输入图像描述

也就是说,测试数据应始终领先于训练数据.

我的想法是:

  1. 编写我自己的k-fold版本类并将其传递给GridSearchCV,这样我就可以享受管道的便利.问题是让GridSearchCV使用指定的训练和测试数据指数似乎很困难.

  2. 写一个新类GridSearchWalkForwardTest,它类似于GridSearchCV,我正在研究源代码grid_search.py​​并发现它有点复杂.

任何建议都是受欢迎的.

python time-series scikit-learn cross-validation

26
推荐指数
2
解决办法
5216
查看次数

R内部处理稀疏矩阵

我一直在比较Python和R的几个PCA实现的性能,并注意到一个有趣的行为:
虽然在Python中计算稀疏矩阵的PCA似乎是不可能的(唯一的方法是scikit-learn的 TruncatedSVD,但它确实如此)不支持平均居中要求等同于PCA的协方差解决方案.他们的论证是,它会破坏矩阵的稀疏性.其他实现如Facebook的PCA算法或scikit中的PCA/randomPCA方法学习不支持稀疏矩阵出于类似的原因.

虽然所有这些对我来说都是有意义的,但是几个R包,如irlba,rsvd等,能够处理稀疏矩阵(例如生成rsparsematrix),甚至允许特定的center=True参数.

我的问题是,R如何在内部处理它,因为它似乎比类似的Python实现更有效.R是否仍然通过绝对缩放来保持稀疏性(这理论上会伪造结果,但至少保持稀疏性)?或者有没有任何方法可以明确地为零值存储均值,并且只存储一次(而不是分别存储每个值)?

为了得到推迟:R内部如何存储具有均值中心的矩阵而不会爆炸RAM使用.希望足够简洁....

python r sparse-matrix pca scikit-learn

26
推荐指数
1
解决办法
631
查看次数

ModuleNotFoundError:没有名为“sklearn.externals.six”的模块

我不断收到错误

ModuleNotFoundError: No module named 'sklearn.externals.six'
Run Code Online (Sandbox Code Playgroud)

运行以下代码时:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
import mglearn
import numpy as np
from IPython.display import display
import matplotlib as pl
import sklearn

iris_dataset = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)
Run Code Online (Sandbox Code Playgroud)

是否有我尚未导入或安装的模块?

python importerror scikit-learn

26
推荐指数
5
解决办法
6万
查看次数

sklearn.manifold.TSNE TypeError:ufunc“multiply”不包含签名匹配类型的循环(dtype('<U32'),dtype('<U32'))...)

我已经运行了sklearn.manifold.TSNEsklearn 文档中的示例代码,但是我收到了问题标题中描述的错误。

我已经尝试将我的 sklearn 版本更新到最新版本(由!pip install -U scikit-learn)(scikit-learn=1.0.1)。然而,问题仍然存在。

有谁知道如何修理它?

  • 蟒蛇 = 3.7.12
  • sklearn=1.0.1

示例代码:

import numpy as np
from sklearn.manifold import TSNE
X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
X_embedded = TSNE(n_components=2, learning_rate='auto',
              init='random').fit_transform(X)
X_embedded.shape
Run Code Online (Sandbox Code Playgroud)

错误行发生在:

X_embedded = TSNE(n_components=2, learning_rate='auto',
              init='random').fit_transform(X)
Run Code Online (Sandbox Code Playgroud)

错误信息:

UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')
Run Code Online (Sandbox Code Playgroud)

python scikit-learn

26
推荐指数
1
解决办法
9589
查看次数

SciPy和scikit-learn - ValueError:尺寸不匹配

我使用SciPyscikit-learn来训练和应用Multinomial朴素贝叶斯分类器进行二进制文本分类.准确地说,我使用该模块sklearn.feature_extraction.text.CountVectorizer创建稀疏矩阵,该稀疏矩阵保存来自文本的单词特征计数,模块sklearn.naive_bayes.MultinomialNB作为分类器实现,用于训练分类器对训练数据并将其应用于测试数据.

输入CountVectorizer是一个表示为unicode字符串的文本文档列表.训练数据远大于测试数据.我的代码看起来像这样(简化):

vectorizer = CountVectorizer(**kwargs)

# sparse matrix with training data
X_train = vectorizer.fit_transform(list_of_documents_for_training)

# vector holding target values (=classes, either -1 or 1) for training documents
# this vector has the same number of elements as the list of documents
y_train = numpy.array([1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, ...])

# sparse matrix with test data
X_test = vectorizer.fit_transform(list_of_documents_for_testing)

# Training stage of …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy scikit-learn

25
推荐指数
1
解决办法
1万
查看次数

如何在scikit-learn中对SVM应用标准化?

我正在使用当前稳定版0.13的scikit-learn.我正在使用类将线性支持向量分类器应用于某些数据sklearn.svm.LinearSVC.

关于 scikit-learn文档中的预处理章节中,我已经阅读了以下内容:

在学习算法的目标函数中使用的许多元素(例如支持向量机的RBF内核或线性模型的l1和l2正则化器)假设所有特征都以零为中心并且具有相同顺序的方差.如果某个要素的方差比其他要大一个数量级,那么它可能会主导目标函数并使估算工具无法按预期正确地学习其他要素.

问题1:标准化对于SVM通常是否有用,对于那些具有线性内核函数的人来说也是如此?

问题2:据我所知,我必须计算训练数据的均值和标准差,并使用该类对测试数据应用相同的转换sklearn.preprocessing.StandardScaler.但是,我不明白的是,在将训练数据提供给SVM分类器之前,我是否还必须转换训练数据或仅转换测试数据.

也就是说,我必须这样做:

scaler = StandardScaler()
scaler.fit(X_train)                # only compute mean and std here
X_test = scaler.transform(X_test)  # perform standardization by centering and scaling

clf = LinearSVC()
clf.fit(X_train, y_train)
clf.predict(X_test)
Run Code Online (Sandbox Code Playgroud)

或者我必须这样做:

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)  # compute mean, std and transform training data as well
X_test = scaler.transform(X_test)  # same as above

clf = LinearSVC()
clf.fit(X_train, y_train)
clf.predict(X_test)
Run Code Online (Sandbox Code Playgroud)

简而言之,我是否必须使用scaler.fit(X_train)或使用scaler.fit_transform(X_train)训练数据才能获得合理的结果 …

python classification normalization svm scikit-learn

25
推荐指数
2
解决办法
2万
查看次数

在scikit-learn的CountVectorizer的停止列表中添加单词

Scikit-learn的CountVectorizer类允许您将字符串'english'传递给参数stop_words.我想在此预定义列表中添加一些内容.谁能告诉我怎么做?

python stop-words scikit-learn

25
推荐指数
1
解决办法
1万
查看次数

拆分数据集中的Python随机状态

我是python的新手.任何人都可以告诉我为什么我们在分裂列车和测试集中将随机状态设置为零.

X_train, X_test, y_train, y_test = \
    train_test_split(X, y, test_size=0.30, random_state=0)
Run Code Online (Sandbox Code Playgroud)

我已经看到过这样的情况,其中随机状态设置为1!

X_train, X_test, y_train, y_test = \
    train_test_split(X, y, test_size=0.30, random_state=1)
Run Code Online (Sandbox Code Playgroud)

交叉验证中这种随机状态的后果是什么?

python random machine-learning scikit-learn

25
推荐指数
6
解决办法
6万
查看次数

大熊猫的分层抽样

我已经查看了Sklearn分层抽样文档以及大熊猫文档以及来自Pandas的分层样本基于列的sklearn分层抽样,但他们没有解决这个问题.

我正在寻找一种快速的pandas/sklearn/numpy方法,从数据集中生成大小为n的分层样本.但是,对于小于指定采样数的行,它应该采用所有条目.

具体例子:

在此输入图像描述

谢谢!:)

python numpy pandas scikit-learn

25
推荐指数
3
解决办法
2万
查看次数