Объявление переменной внутри или вне цикла foreach: что быстрее / лучше?

Это, к сожалению, прямо прямо сейчас с GridSearchCV или любым встроенным методом / объектом sklearn.

Хотя есть разговоры о наличии нескольких выходов счетчика, эта функция, вероятно, не скоро появится.

Итак, вам придется сделать это самостоятельно, есть несколько способов:

1) Вы можете взглянуть на код cross_val_score и выполнить цикл перекрестной проверки самостоятельно, вызывая (/ g5)

2) [не рекомендуется] Вы также можете создать свой собственный бомбардир из интересующих вас бомбардировщиков и заставить их выводить оценки в виде массива. Затем вы обнаружите проблему, описанную здесь: sklearn - перекрестная проверка с несколькими баллами

3) Так как вы можете закодировать свои собственные счетчики , вы может сделать бомбардир, который выводит один из ваших оценок (тот, по которому вы хотите GridSearchCV принимать решения), и который хранит все остальные оценки, которые вас интересуют в отдельном месте, которое может быть статической / глобальной переменной, или даже файл.

Число 3 кажется наименее утомительным и наиболее перспективным:

import numpy as np
from sklearn.metrics import r2_score, mean_squared_error
secret_mses = []

def r2_secret_mse(estimator, X_test, y_test):
    predictions = estimator.predict(X_test)
    secret_mses.append(mean_squared_error(y_test, predictions))
    return r2_score(y_test, predictions)

X = np.random.randn(20, 10)
y = np.random.randn(20)

from sklearn.cross_validation import cross_val_score
from sklearn.linear_model import Ridge

r2_scores = cross_val_score(Ridge(), X, y, scoring=r2_secret_mse, cv=5)

Вы найдете оценки R2 в r2_scores и соответствующие MSE в secret_mses ,

Обратите внимание, что это может стать беспорядочным, если вы идете параллельно. В этом случае вам нужно будет записать оценки в определенное место в memmap, например.

82
задан codekaizen 2 July 2010 в 09:24
поделиться

8 ответов

С точки зрения производительности оба примера скомпилированы в один и тот же IL, поэтому нет никакой разницы.

Второй вариант лучше, поскольку он более четко выражает ваше намерение if u используется только внутри цикла.

102
ответ дан 24 November 2019 в 08:54
поделиться

In any case, the best way would be to use a constructor that takes a Name... or, otherwise, exploit curly-brace notation:

foreach (string s in l)
{
    list.Add(new User(s));
}

or

foreach (string s in l)
{
    list.Add(new User() { Name = s });
}

or even better, LINQ:

var list = l.Select( s => new User { Name = s});

Now, while your first example could, in some cases, be unperceptibly faster, the second one is better because it's more readable, and the compiler may discard the variable (and omit it altogether) since it's not used outsid the foreach's scope.

14
ответ дан 24 November 2019 в 08:54
поделиться

A declaration does not cause any code to be executed, so it's not a performance issue.

The second one is what you mean, and you're less likely to make a stupid error if you do it the second way, so use that. Always try to declare variables in the smallest scope necessary.

And besides, the better way is to use Linq:

List<User> users = l.Select(name => new User{ Name = name }).ToList();
6
ответ дан 24 November 2019 в 08:54
поделиться

The 2nd one is better. You are meaning to have a new user in each iteration.

1
ответ дан 24 November 2019 в 08:54
поделиться

Technically, the first example will save a few nanoseconds because the stack frame will not have to be moved to allocate a new variable, but this is such a tiny amount of CPU time you won't notice it, that's if the compiler doesn't optimize any difference away anyays.

1
ответ дан 24 November 2019 в 08:54
поделиться

Whenever you've a question about performance, the only thing to do is measure - run a loop around your test and time it.

To answer your question - without measuring :-) or looking at the generated ilasm - any difference wouldn't be noticeable in a meaningful number of iterations and the most expensive operation in your code there is likely to be the user allocation by a few orders of magnitude, so concentrate on code clarity (as you should in general) and go with 2.

Oh, its late and I guess I'm just trying to say don't worry about this sort of thing or get caught up in details like this.

K

5
ответ дан 24 November 2019 в 08:54
поделиться

Не должно быть заметной разницы в производительности.

0
ответ дан 24 November 2019 в 08:54
поделиться

In this scenario, the second version is better.

In general, if you only need to access the value within the body of the iteration, then choose the second version. On the other hand, if there is some final state the variable will hold beyond the body of the loop, then declare then use the first version.

1
ответ дан 24 November 2019 в 08:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: