小编Viv*_*mar的帖子

sklearn 维度问题“找到带有暗淡 3 的数组。估计器预期 <= 2”

我正在尝试使用 KNN 将 .wav 文件正确分类为两组,组 0 和组 1。

我提取了数据,创建了模型,拟合了模型,但是当我尝试使用 .predict() 方法时,我收到以下错误:

Traceback (most recent call last):   
File "/..../....../KNN.py", line 20, in <module>
    classifier.fit(X_train, y_train)   
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/neighbors/base.py", line 761, in fit
    X, y = check_X_y(X, y, "csr", multi_output=True)   
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 521, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)   
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 405, in check_array
    % (array.ndim, estimator_name)) 
ValueError: Found array with dim 3. Estimator expected <= 2.
Run Code Online (Sandbox Code Playgroud)

我发现这两个 stackoverflow 帖子描述了类似的问题:

sklearn Logistic Regression “ValueError: Found array with dim 3. Estimator expected <= …

python signal-processing numpy machine-learning scikit-learn

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

TfidfVectorizer NotFittedError

我正在使用sklearn Pipeline和FeatureUnion从文本文件创建功能,我想打印出功能名称.

首先,我将所有转换收集到一个列表中.

In [225]:components
Out[225]: 
[TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
         dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
         lowercase=True, max_df=0.85, max_features=None, min_df=6,
         ngram_range=(1, 1), norm='l1', preprocessor=None, smooth_idf=True,
         stop_words='english', strip_accents=None, sublinear_tf=True,
         token_pattern=u'(?u)[#a-zA-Z0-9/\\-]{2,}',
         tokenizer=StemmingTokenizer(proc_type=stem, token_pattern=(?u)[a-zA-Z0-9/\-]{2,}),
         use_idf=True, vocabulary=None),
 TruncatedSVD(algorithm='randomized', n_components=150, n_iter=5,
        random_state=None, tol=0.0),
 TextStatsFeatures(),
 DictVectorizer(dtype=<type 'numpy.float64'>, separator='=', sort=True,
         sparse=True),
 DictVectorizer(dtype=<type 'numpy.float64'>, separator='=', sort=True,
         sparse=True),
 TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
         dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
         lowercase=True, max_df=0.85, max_features=None, min_df=6,
         ngram_range=(1, 2), norm='l1', preprocessor=None, smooth_idf=True,
         stop_words='english', strip_accents=None, sublinear_tf=True,
         token_pattern=u'(?u)[a-zA-Z0-9/\\-]{2,}',
         tokenizer=StemmingTokenizer(proc_type=stem, token_pattern=(?u)[a-zA-Z0-9/\-]{2,}),
         use_idf=True, vocabulary=None)]
Run Code Online (Sandbox Code Playgroud)

例如,第一个组件是TfidfVectorizer()对象.

components[0]
Out[226]: 
TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
        dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content', …
Run Code Online (Sandbox Code Playgroud)

python pipeline scikit-learn

3
推荐指数
1
解决办法
1524
查看次数

使用GridSearch时使用Scikit-learn的模型帮助

作为安然项目的一部分,构建了附加模型,下面是步骤的摘要,

以下型号给出了非常完美的分数

cv = StratifiedShuffleSplit(n_splits = 100, test_size = 0.2, random_state = 42)
gcv = GridSearchCV(pipe, clf_params,cv=cv)

gcv.fit(features,labels) ---> with the full dataset

for train_ind, test_ind in cv.split(features,labels):
    x_train, x_test = features[train_ind], features[test_ind]
    y_train, y_test = labels[train_ind],labels[test_ind]

    gcv.best_estimator_.predict(x_test)
Run Code Online (Sandbox Code Playgroud)

下面的模型给出了更合理但低分

cv = StratifiedShuffleSplit(n_splits = 100, test_size = 0.2, random_state = 42)
gcv = GridSearchCV(pipe, clf_params,cv=cv)

gcv.fit(features,labels) ---> with the full dataset

for train_ind, test_ind in cv.split(features,labels):
     x_train, x_test = features[train_ind], features[test_ind]
     y_train, y_test = labels[train_ind],labels[test_ind]

     gcv.best_estimator_.fit(x_train,y_train)
     gcv.best_estimator_.predict(x_test)
Run Code Online (Sandbox Code Playgroud)
  1. 使用Kbest查找分数并对功能进行排序并尝试更高和更低分数的组合.

  2. 使用StratifiedShuffle将SVM与GridSearch一起使用

  3. 使用best_estimator_来预测和计算精度和召回率.

问题是估算器正在吐出完美的分数,在某些情况下是1 …

python machine-learning scikit-learn cross-validation grid-search

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

Keras回归使用Scikit了解StandardScaler与管道和无管道

我正在比较两个关于KerasRegressor使用Scikit-Learn的程序的性能StandardScaler:一个程序与Scikit-Learn Pipeline和一个程序没有Pipeline.

计划1:

estimators = []
estimators.append(('standardise', StandardScaler()))
estimators.append(('multiLayerPerceptron', KerasRegressor(build_fn=build_nn, nb_epoch=num_epochs, batch_size=10, verbose=0)))
pipeline = Pipeline(estimators)
log = pipeline.fit(X_train, Y_train)
Y_deep = pipeline.predict(X_test)
Run Code Online (Sandbox Code Playgroud)

计划2:

scale = StandardScaler()
X_train = scale.fit_transform(X_train)
X_test = scale.fit_transform(X_test)
model_np = KerasRegressor(build_fn=build_nn, nb_epoch=num_epochs, batch_size=10, verbose=0)
log = model_np.fit(X_train, Y_train)
Y_deep = model_np.predict(X_test)
Run Code Online (Sandbox Code Playgroud)

我的问题是,程序1可以使R2得分为0.98(平均3次试验),而程序2只能达到R2得分为0.84(平均3次试验).有谁可以解释这两个程序之间的区别?

python pipeline scikit-learn keras

3
推荐指数
1
解决办法
3057
查看次数

ValueError:n_splits = 10不能大于每个类中的成员数

我试图运行以下代码:

from sklearn.model_selection import StratifiedKFold 
X = ["hey", "join now", "hello", "join today", "join us now", "not today", "join this trial", " hey hey", " no", "hola", "bye", "join today", "no","join join"]
y = ["n", "r", "n", "r", "r", "n", "n", "n", "n", "r", "n", "n", "n", "r"]

skf = StratifiedKFold(n_splits=10)

for train, test in skf.split(X,y):  
    print("%s %s" % (train,test))
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

ValueError: n_splits=10 cannot be greater than the number of members in each class.
Run Code Online (Sandbox Code Playgroud)

我在这里看了scikit-learn错误:y中人口最少的类只有1个成员,但我仍然不确定我的代码有什么问题.

我的名单都有14个长度print(len(X)) print(len(y)) …

python scikit-learn cross-validation

3
推荐指数
1
解决办法
7484
查看次数

sklearn 模型数据转换错误:CountVectorizer - 未安装词汇

我已经训练了一个主题分类模型。然后当我要将新数据转换为向量进行预测时,它出错了。它显示“NotFittedError: CountVectorizer - Vocabulary is not fit”。但是当我通过将训练数据拆分为训练模型中的测试数据来进行预测时,它起作用了。下面是代码:

from sklearn.externals import joblib
from sklearn.feature_extraction.text import CountVectorizer

import pandas as pd
import numpy as np

# read new dataset
testdf = pd.read_csv('C://Users/KW198/Documents/topic_model/training_data/testdata.csv', encoding='cp950')

testdf.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1800 entries, 0 to 1799
Data columns (total 2 columns):
keywords    1800 non-null object
topics      1800 non-null int64
dtypes: int64(1), object(1)
memory usage: 28.2+ KB

# read columns
kw = testdf['keywords']
label = testdf['topics']

# ?????????
vectorizer = CountVectorizer(min_df=1, stop_words='english')
x_testkw_vec = vectorizer.transform(kw)
Run Code Online (Sandbox Code Playgroud)

这是一个错误

--------------------------------------------------------------------------- …
Run Code Online (Sandbox Code Playgroud)

python machine-learning scikit-learn text-classification countvectorizer

3
推荐指数
1
解决办法
3598
查看次数

sklearn中带有数据标签的定制变压器Mixin

我正在做一个小项目,试图在我的数据不平衡的情况下应用SMOTE“综合少数族裔过采样技术”。

我为SMOTE功能创建了一个定制的TransformerMixin ..

class smote(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        print(X.shape, ' ', type(X)) # (57, 28)   <class 'numpy.ndarray'>
        print(len(y), ' ', type)     #    57      <class 'list'>
        smote = SMOTE(kind='regular', n_jobs=-1)
        X, y = smote.fit_sample(X, y)

        return X

    def transform(self, X):
        return X
Run Code Online (Sandbox Code Playgroud)
model = Pipeline([
        ('posFeat1', featureVECTOR()),
        ('sca1', StandardScaler()),
        ('smote', smote()),
        ('classification', SGDClassifier(loss='hinge', max_iter=1, random_state = 38, tol = None))
    ])
    model.fit(train_df, train_df['label'].values.tolist())
    predicted = model.predict(test_df)
Run Code Online (Sandbox Code Playgroud)

我在FIT函数上实现了SMOTE,因为我不希望将其应用于测试数据。

不幸的是,我得到了这个错误:

     model.fit(train_df, train_df['label'].values.tolist())
  File "C:\Python35\lib\site-packages\sklearn\pipeline.py", line 248, in fit
    Xt, fit_params = …
Run Code Online (Sandbox Code Playgroud)

python pipeline scikit-learn

3
推荐指数
1
解决办法
1168
查看次数

CountVectorizer上的词法化不会删除停用词

我正在尝试从Skit-learn向CountVectorizer添加Lematization,如下所示

import nltk
from pattern.es import lemma
from nltk import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import WordNetLemmatizer

class LemmaTokenizer(object):
    def __call__(self, text):
        return [lemma(t) for t in word_tokenize(text)]

vectorizer = CountVectorizer(stop_words=stopwords.words('spanish'),tokenizer=LemmaTokenizer())

sentence = ["EVOLUCIÓN de los sucesos y la EXPANSIÓN, ellos juegan y yo les dije lo que hago","hola, qué tal vas?"]

vectorizer.fit_transform(sentence)
Run Code Online (Sandbox Code Playgroud)

这是输出:

[u',', u'?', u'car', u'decir', u'der', u'evoluci\xf3n', u'expansi\xf3n', u'hacer', u'holar', u'ir', u'jugar', u'lar', u'ler', u'sucesos', u'tal', u'yar']
Run Code Online (Sandbox Code Playgroud)

更新

这是出现的停用词,已经过词缀化:

u'lar',u'ler',u'der'

它限制所有单词,并且不会删除停用词。那么,有什么想法吗?

nltk stop-words lemmatization scikit-learn countvectorizer

3
推荐指数
1
解决办法
1946
查看次数

如何在 Sci-kit 中使用多输出回归器的交叉验证?

首先是我的设置:X 是我的特征表。它有 150 000 个特征和 96 个样本。所以有 150 000 列和 96 行。

y 是我的目标表。它有 4 个标签,当然还有 96 个样品。所以 4x96(列 x 行)。

分成训练数据和测试数据后,我使用 MLPRegressor。基于 Sci-kit 的文档,它是一个原生的多输出回归器。因此我可以使用它通过 150 000 个特征的新样本来预测我的四个所需输出值。我的代码:

mlp = MLPRegressor(hidden_layer_sizes=(2000, 2000), solver= 'lbfgs', max_iter=100)
mlp.fit(X_train,y_train)
Run Code Online (Sandbox Code Playgroud)

然后我使用交叉验证。

cross_validation.cross_val_score(mlp, X, y, scoring='r2')
Run Code Online (Sandbox Code Playgroud)

输出是一个包含 3 个条目的列表(参数 cv=3)。我真的不明白我的 4 个标签是如何由这 3 个值表示的。我期望的格式如下:标签 1: 3 个条目,标签 2: 3 个条目,标签 3 和 4 也相同。因此,对于不同的分割,我将所有标签的 R^2 值三次获取测试和训练数据。

我错过了什么吗?我需要使用多输出回归器吗? (请参阅此处的文档)

这里交叉验证的文档。

谢谢。

python machine-learning neural-network scikit-learn cross-validation

3
推荐指数
1
解决办法
3644
查看次数

ap_uniform_sampler() 缺少 1 个必需的位置参数:python 的 Ray Tune 包中的“高”

我正在尝试使用 Ray Tune包对使用纯 Tensorflow 实现的 LSTM 进行超参数调整。我用的超频调度和HyperOptSearch算法这一点,我也使用可训练类的方法。当我尝试运行它时,出现以下错误:

类型错误:ap_uniform_sampler() 缺少 1 个必需的位置参数:“高”

下面显示的是堆栈跟踪:

FutureWarning:不推荐将 issubdtype 的第二个参数从floatto转换np.floating。将来,它将被视为np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters Process STDOUT 和 STDERR 被重定向到 /tmp/ray/session_2018-12-19_09-43-46_5469/logs。等待 127.0.0.1:14332 处的 redis 服务器响应... 等待 127.0.0.1:25158 处的 redis 服务器响应... 使用 /dev/shm 启动具有 3.220188364 GB 内存的 Plasma 对象存储。无法启动 UI,您可能需要运行“pip install jupyter”。== 状态 == 使用 HyperBand:num_stopped=0 total_brackets=0 第 0 轮:请求的资源:0/4 个 CPU,0/0 个 GPU 此节点上的内存使用量:3.7/8.1 GB

Traceback (most recent call last):   
File …
Run Code Online (Sandbox Code Playgroud)

python-3.x ray hyperparameters tensorflow hyperopt

3
推荐指数
1
解决办法
1854
查看次数