给出一个简单的CSV文件:
A,B,C
Hello,Hi,0
Hola,Bueno,1
Run Code Online (Sandbox Code Playgroud)
显然,真正的数据集远比这复杂得多,但是这个数据集再现了错误.我正在尝试为它构建一个随机的森林分类器,如下所示:
cols = ['A','B','C']
col_types = {'A': str, 'B': str, 'C': int}
test = pd.read_csv('test.csv', dtype=col_types)
train_y = test['C'] == 1
train_x = test[cols]
clf_rf = RandomForestClassifier(n_estimators=50)
clf_rf.fit(train_x, train_y)
Run Code Online (Sandbox Code Playgroud)
但是我在调用fit()时得到这个回溯:
ValueError: could not convert string to float: 'Bueno'
Run Code Online (Sandbox Code Playgroud)
scikit-learn版本是0.16.1.
我正在学习不同的方法来将分类变量转换为机器学习分类器的数字.我遇到了这个pd.get_dummies方法,sklearn.preprocessing.OneHotEncoder()我想看看它们在性能和使用方面有何不同.
我找到了一个关于如何OneHotEnocder()在https://xgdgsc.wordpress.com/2015/03/20/note-on-using-onehotencoder-in-scikit-learn-to-work-on-categorical-features/上使用的教程,因为该sklearn文件并没有这个功能也很有帮助.我有一种感觉,我没有正确地做到这一点......但是
有人可以解释使用pd.dummies过的优点和缺点,sklearn.preprocessing.OneHotEncoder()反之亦然吗?我知道这OneHotEncoder()给你一个稀疏矩阵但除此之外我不确定它是如何使用的,以及该pandas方法的好处是什么.我用它效率不高吗?
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
sns.set()
%matplotlib inline
#Iris Plot
iris = load_iris()
n_samples, m_features = iris.data.shape
#Load Data
X, y = iris.data, iris.target
D_target_dummy = dict(zip(np.arange(iris.target_names.shape[0]), iris.target_names))
DF_data = pd.DataFrame(X,columns=iris.feature_names)
DF_data["target"] = pd.Series(y).map(D_target_dummy)
#sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) \
#0 5.1 3.5 1.4 …Run Code Online (Sandbox Code Playgroud) 我一直在使用scikit-learn库.我正在尝试在scikit-learn库下使用高斯朴素贝叶斯模块,但我遇到了以下错误.TypeError:无法使用灵活类型执行reduce
以下是代码段.
training = GaussianNB()
training = training.fit(trainData, target)
prediction = training.predict(testData)
Run Code Online (Sandbox Code Playgroud)
这是目标
['ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML']
Run Code Online (Sandbox Code Playgroud)
这是trainData
[['-214' '-153' '-58' ..., '36' '191' '-37']
['-139' '-73' '-1' ..., '11' '76' '-14']
['-76' '-49' '-307' ..., '41' '228' '-41']
...,
['-32' '-49' '49' ..., '-26' '133' …Run Code Online (Sandbox Code Playgroud) 使用train_test_split()时如何获取数据的原始索引?
我所拥有的是以下内容
from sklearn.cross_validation import train_test_split
import numpy as np
data = np.reshape(np.randn(20),(10,2)) # 10 training examples
labels = np.random.randint(2, size=10) # 10 labels
x1, x2, y1, y2 = train_test_split(data, labels, size=0.2)
Run Code Online (Sandbox Code Playgroud)
但这并没有给出原始数据的索引.一种解决方法是将索引添加到数据(例如data = [(i, d) for i, d in enumerate(data)]),然后将其传递到内部train_test_split,然后再次展开.有没有更清洁的解决方案?
我使用linear_model.LinearRegressionscikit-learn作为预测模型.它的工作原理很完美.我有一个问题是使用accuracy_score指标评估预测结果.这是我的真实数据:
array([1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0])
Run Code Online (Sandbox Code Playgroud)
我的预测数据:
array([ 0.07094605, 0.1994941 , 0.19270157, 0.13379635, 0.04654469,
0.09212494, 0.19952108, 0.12884365, 0.15685076, -0.01274453,
0.32167554, 0.32167554, -0.10023553, 0.09819648, -0.06755516,
0.25390082, 0.17248324])
Run Code Online (Sandbox Code Playgroud)
我的代码:
accuracy_score(y_true, y_pred, normalize=False)
Run Code Online (Sandbox Code Playgroud)
错误信息:
ValueError:无法处理二进制和连续目标的混合
救命 ?谢谢.
python machine-learning prediction linear-regression scikit-learn
在python中使用以下代码用于svm:
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
iris = datasets.load_iris()
X, y = iris.data, iris.target
clf = OneVsRestClassifier(SVC(kernel='linear', probability=True, class_weight='auto'))
clf.fit(X, y)
proba = clf.predict_proba(X)
Run Code Online (Sandbox Code Playgroud)
但这需要花费大量时间.
实际数据维度:
train-set (1422392,29)
test-set (233081,29)
Run Code Online (Sandbox Code Playgroud)
我怎样才能加快速度(平行或其他方式)?请帮忙.我已经尝试过PCA和下采样.
我有6节课.编辑:发现http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html 但我希望进行概率估计,而且对于svm来说似乎并非如此.
编辑:
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC,LinearSVC
from sklearn.linear_model import SGDClassifier
import joblib
import numpy as np
from sklearn import grid_search
import multiprocessing
import numpy as np
import math
def …Run Code Online (Sandbox Code Playgroud) 我想将缩放(使用sklearn.preprocessing中的StandardScaler())应用到pandas数据帧.以下代码返回一个numpy数组,因此我丢失了所有列名和indeces.这不是我想要的.
features = df[["col1", "col2", "col3", "col4"]]
autoscaler = StandardScaler()
features = autoscaler.fit_transform(features)
Run Code Online (Sandbox Code Playgroud)
我在网上找到的"解决方案"是:
features = features.apply(lambda x: autoscaler.fit_transform(x))
Run Code Online (Sandbox Code Playgroud)
它似乎有效,但会导致弃用警告:
/usr/lib/python3.5/site-packages/sklearn/preprocessing/data.py:583:DreprecationWarning:传递1d数组作为数据在0.17中被弃用,并将在0.19中引发ValueError.如果数据具有单个要素,则使用X.reshape(-1,1)重新整形数据;如果包含单个样本,则使用X.reshape(1,-1)重新整形数据.
我因此尝试过:
features = features.apply(lambda x: autoscaler.fit_transform(x.reshape(-1, 1)))
Run Code Online (Sandbox Code Playgroud)
但这给了:
回溯(最近一次调用最后一次):文件"./analyse.py",第91行,在features = features.apply(lambda x:autoscaler.fit_transform(x.reshape(-1,1)))文件"/ usr/lib/python3.5/site-packages/pandas/core/frame.py",第3972行,在apply中返回self._apply_standard(f,axis,reduce = reduce)文件"/usr/lib/python3.5/site- packages/pandas/core/frame.py",第4081行,在_apply_standard结果= self._constructor(data = results,index = index)文件"/usr/lib/python3.5/site-packages/pandas/core/frame .py",第226行,在 init mgr = self._init_dict(data,index,columns,dtype = dtype)文件"/usr/lib/python3.5/site-packages/pandas/core/frame.py",行363,in _init_dict dtype = dtype)文件"/usr/lib/python3.5/site-packages/pandas/core/frame.py",第5163行,在_arrays_to_mgr arrays = _homogenize(arrays,index,dtype)File"/ usr/lib/python3.5/site-packages/pandas/core/frame.py",第5477行,_homogenize raise_cast_failure = False)文件"/usr/lib/python3.5/site-packages/pandas/core/series .s",第2885行,在_sanitize_a中 rray raise Exception('数据必须是1维')例外:数据必须是1维的
如何将缩放应用于pandas数据帧,使数据帧保持不变?如果可能,不复制数据.
我想将一个由一系列元素组成的pandas列分解为多个列,因为它们具有唯一的元素,即one-hot-encode它们(其值1表示存在于行0中的给定元素,在缺少的情况下).
例如,采用数据帧df
Col1 Col2 Col3
C 33 [Apple, Orange, Banana]
A 2.5 [Apple, Grape]
B 42 [Banana]
Run Code Online (Sandbox Code Playgroud)
我想将其转换为:
DF
Col1 Col2 Apple Orange Banana Grape
C 33 1 1 1 0
A 2.5 1 0 0 1
B 42 0 0 1 0
Run Code Online (Sandbox Code Playgroud)
我如何使用pandas/sklearn来实现这一目标?
假设我有一个分类特征,颜色,它取值
['red','blue','green','orange'],
我想用它来预测随机森林里的东西.如果我对它进行单热编码(即我将其更改为四个虚拟变量),我如何告诉sklearn这四个虚拟变量实际上是一个变量?具体来说,当sklearn随机选择要在不同节点使用的特征时,它应该包括红色,蓝色,绿色和橙色虚拟对象,或者它不应包括任何一个.
我听说没有办法做到这一点,但我认为必须有一种方法来处理分类变量,而不是随意将它们编码为数字或类似的东西.
我运行一个python程序,调用sklearn.metrics计算精度和F1分数的方法.这是没有预测样本时的输出:
/xxx/py2-scikit-learn/0.15.2-comp6/lib/python2.6/site-packages/sklearn/metr\
ics/metrics.py:1771: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples.
'precision', 'predicted', average, warn_for)
/xxx/py2-scikit-learn/0.15.2-comp6/lib/python2.6/site-packages/sklearn/metr\
ics/metrics.py:1771: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 due to no predicted samples.
'precision', 'predicted', average, warn_for)
Run Code Online (Sandbox Code Playgroud)
当没有预测样本时,意味着TP + FP为0,所以
在我的情况下,sklearn.metrics也将精度返回到0.8,并记为0.因此FN不为零.
但是为什么scikilearn说F1不明确?
Scikilearn使用F1的定义是什么?
scikit-learn ×10
python ×9
pandas ×3
numpy ×2
prediction ×1
python-2.7 ×1
scipy ×1
statistics ×1
svm ×1