我正在阅读使用 Scikit-Learn 和 TensorFlow 进行机器学习实践:构建智能系统的概念、工具和技术。在一个例子中,我在 for 循环中看到了这个语法。
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
我打印了 train_index 和 test_index,它们是索引数组。这个for循环是什么意思?train_index 和 test_index 有不同数量的元素,迭代如何工作?这段代码等价于下面的代码吗?
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
train_index, test_index = split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
这是一个 for 循环中 2 个变量的简单情况:
In [173]: for a,b in [[0,1],[10,12]]:
...: print(a,b)
...:
0 1
10 12
如果出于同样的原因工作:
In [174]: a,b = [10,12]
迭代返回某种元组或列表,并将a,b in ...
这 2 个值解包为匹配数量的变量。
for i, v in enumerate(['a','b','c']):
print(i,v)
是循环中解包的另一个常见用途。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句