我正在学习python中的机器学习并使用scikit学习包。我已经使用R来实现这个目的,并且很容易找到它的数据帧结构。 Scikit学习使用numpy数组,我觉得有点困难。在python中,我们有一个类似于R dataframe的pandas。此代码取自此website。
[R
library(e1071)
library(MASS)
data(iris)
mysvm <- svm(Species ~ ., iris)
mysvm.pred <- predict(mysvm, iris)
table(mysvm.pred,iris$Species)
# mysvm.pred setosa versicolor virginica
# setosa 50 0 0
# versicolor 0 48 2
# virginica 0 2 48
的Python
from sklearn import svm, datasets
from sklearn.metrics import confusion_matrix
iris = datasets.load_iris()
mysvm = svm.SVC().fit(iris.data, iris.target)
mysvm_pred = mysvm.predict(iris.data)
print confusion_matrix(mysvm_pred, iris.target)
# [[50 0 0]
# [ 0 48 2]
# [ 0 0 50]]
如何使用上面的python代码和pandas dataframe并使用SVM回归
EDITED
这就是我所做的
from sklearn import svm, datasets
from sklearn.metrics import confusion_matrix
import pandas as pd
iris = datasets.load_iris()
X=pd.DataFrame(iris.data,columns=iris.feature_names)
y=pd.DataFrame(iris.target)
X.head()
y.head()
mysvm = svm.SVC().fit(X,y )
mysvm_pred = mysvm.predict(X)
print confusion_matrix(mysvm_pred, y)
但它给出了这个错误
>>> mysvm = svm.SVC().fit(X,y )
/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py:514: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y_ = column_or_1d(y, warn=True)
>>> mysvm_pred = mysvm.predict(X)
>>> print confusion_matrix(mysvm_pred, y)
/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py:2645: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instead. To find the rank of a matrix see `numpy.linalg.matrix_rank`.
VisibleDeprecationWarning)
[[50 0 0]
[ 0 48 0]
[ 0 2 50]]
答案 0 :(得分:1)
您可以像这样使用交叉验证:
from sklearn import svm, datasets, cross_validation
from sklearn import metrics
import pandas as pd
clf = svm.SVC()
cv_scores = cross_validation.cross_val_score(clf,iris.data,iris.target,cv=10)
cv_preds = cross_validation.cross_val_predict(clf,iris.data,iris.target,cv =10)
我不确定你想用pandas做什么,但如果你想将数据集加载到pandas数据帧,你可以这样做:
clf.fit(iris.data,iris.target)
preds = clf.predict(iris.data)
df = pd.DataFrame(iris.data)
df['target'] = iris.target
df['preds'] = preds
print(df)
print confusion_matrix(df['target'],df['preds'])
计算准确度:
accuracy = metrics.accuracy_score(iris.target, preds)
print(accuracy)
答案 1 :(得分:0)
关于错误:
>>> print confusion_matrix(mysvm_pred, y)
/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py:2645: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instead. To find the rank of a matrix see `numpy.linalg.matrix_rank`.
VisibleDeprecationWarning)
您可以参考以下链接: