Ради ответа давайте представим ваш код в форме, в которой другие могут воспроизвести проблему:
from sklearn import svm
from sklearn.model_selection import cross_val_score
np.random.seed(42)
X = np.random.rand(2000, 2)
y = np.random.randint(0,2,2000)
C = np.array([1, 10, 100, 1000])
gamma = np.array([1e-3, 1e-4])
avg_rbf_f1 = []
for a in C:
for b in gamma:
rbf_model = svm.SVC(kernel='rbf',C=a, gamma=b)
rbf_scores = cross_val_score(rbf_model, X, y, cv=10, scoring='f1_macro')
avg_rbf_f1.append(np.mean(rbf_scores))
best_gamma = gamma[np.argmax(avg_rbf_f1)]
best_C = C[np.argmax(avg_rbf_f1)]
print('The gamma with the highest accuracy is {}'.format(best_gamma))
print('The C with the highest accuracy is {}'.format(best_C))
И сама ошибка:
IndexError Traceback (most recent call last)
<ipython-input-30-84d1adf5e2d9> in <module>()
17 avg_rbf_f1.append(np.mean(rbf_scores))
18
---> 19 best_gamma = gamma[np.argmax(avg_rbf_f1)]
20 best_C = C[np.argmax(avg_rbf_f1)]
21
IndexError: index 6 is out of bounds for axis 0 with size 2
Гиперпараметр gamma
имеет 2 возможных значения, в то время как avg_rbf_f1
- это список из 8. В том виде, в котором вы в настоящее время реализовали поиск по сетке, вы не сможете вернуть свои лучшие параметры.Вот как вы можете изменить свой код так, чтобы он работал:
from sklearn import svm
from sklearn.model_selection import cross_val_score
np.random.rand(42)
X = np.random.rand(2000, 2)
y = np.random.randint(0,2,2000)
C = np.array([1, 10, 100, 1000])
gamma = np.array([1e-3, 1e-4])
avg_rbf_f1 = []
search = []
for a in C:
for b in gamma:
search.append((a,b))
rbf_model = svm.SVC(kernel='rbf',C=a, gamma=b)
rbf_scores = cross_val_score(rbf_model, X, y, cv=10, scoring='f1_macro')
avg_rbf_f1.append(np.mean(rbf_scores))
best_C, best_gamma = search[np.argmax(avg_rbf_f1)]
print('The gamma with the highest accuracy is {}'.format(best_gamma))
print('The C with the highest accuracy is {}'.format(best_C))
Это далеко не оптимально.Я просто добавил search
список, который собирает комбинацию C и гаммы.
Что было бы тогда оптимальным?Используйте GridSearchCV .Снимает много кода со спины.