4つ一体どのcsvから順ようにひとつずつテストデータとして用い、残りの3つのデータを訓練データとして用いたい使えばいいのですが、
l_in_not = [s for s in l if i not in s]
で "TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed"というエラーが出てしまいました。
Traceback (most recent call last):
File "rf_loso.py", line 88, in <module>
l_in_not = [s for s in l if i not in s]
File "rf_loso.py", line 88, in <listcomp>
l_in_not = [s for s in l if i not in s]
File "/Users/m-sakai/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages/pandas/core/generic.py", line 1075, in __contains__
return key in self._info_axis
File "/Users/m-sakai/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 1694, in __contains__
hash(key)
File "/Users/m-sakai/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages/pandas/core/generic.py", line 1045, in __hash__
' hashed'.format(self.__class__.__name__))
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
コードは以下ですでしょう?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation, metrics
import itertools
import matplotlib.pyplot as plt
from sklearn import metrics, cross_validation
from sklearn.metrics import confusion_matrix
from sklearn.grid_search import GridSearchCVLeaveOneOut
from sklearn.externalsmodel_selection import joblib
# コンフュージョンマトリックスのメソッド
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# path
data_dir = "csv_data/"
fig_dir = "figsvm/"
# CSVデータを読み込む --- (※1)
a = pd.read_csv('AAA.csv')
b = pd.read_csv('BBB.csv')
c = pd.read_csv('CCC.csv')
d = pd.read_csv('DDD.csv')
list = [a,b,c,d]
for i in list:
l = [a,b,c,d]
l_in_not = [s for s in l if i not in s]
for u in l_in_not:
train_data = u["california"]
train_label = u["NY"]
test_data = i["california"]
test_label = i["NY"]
test = i[scaner]
class_names = ["A","B"]
# クロスバリデーションを行う --- (※3)
#clf = svm.SVC()
clf = RandomForestClassifier()
#scores = cross_validation.cross_val_score(
#clf, data, label, cv=10)
params ={
'n_estimators' : [50,200],
'max_depth' : [20]
}
# グリッドサーチを行う --- (※4)
clf = GridSearchCV(RandomForestClassifier(), params)
clf.fit(train_data, train_label)
print("学習器=", clf.best_estimator_)
scores = cross_validation.cross_val_score(
clf, train_data, train_label, cv=10)
#clf = GridSearchCV(svm.SVC(), params, n_jobs=-1 )
#clf.fit(train_data, train_label)
# トレーニングデータで確認 --- (※5)
y_pred = clf.predict(train_data)
ac_score = metrics.accuracy_score(y_pred, train_label)
#print("正解率=",ac_score)
# テストデータで確認 --- (※5)
y_pred = clf.predict(test_data)
ac_score = metrics.accuracy_score(y_pred, test_label)
print("正解率=",ac_score)
# コンフュージョンマトリックスをfigフォルダに保存する
cnf_matrix = confusion_matrix(test_label, y_pred)
np.set_printoptions(precision=2)
plt.figure() #Plot non-normalized confusion matrix
plot_confusion_matrix(cnf_matrix, classes=class_names,
title='Confusion matrix, without normalization')
plt.savefig(""+str(i)+".png")
plt.figure() # Plot normalized confusion matrix
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
title='Normalized confusion matrix')
plt.savefig("fig/rf_3_normalized/"+str(i) +".png")
cl_report = metrics.classification_report(test_label,y_pred)
print("各正解率=" ,scores)
print("正解率=", scores.mean())
print("レポート=\n",cl_report)
LeaveOneGroupOut
というようにインポートしたいのですが、ネット上でいくら探してもそれらしい記事が見つからず、お力をお借りしたいです