我试图比较ANN和200个不同数据集的逻辑回归的性能。每个数据集都命名为Dataseti where i is a number from 15 to 214
。因此我运行循环:
for i in range(15,215):
让ANN和逻辑回归进行训练并对数据进行分类。我想要抓住的是逻辑回归的误差:
"ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: 0.0"
当捕获错误时,我希望跳过此数据集,然后继续下一个(i + 1)。
这有可能吗?我对编程很新,并且不清楚如何处理这个异常。我已经考虑过使用if else配方以某种方式做到这一点:
if(dataset[:,-1].max() == 1)
....
else:
但我不知道该怎么接受else表达式。如果有人能帮助我解决这个问题会很棒。谢谢!
答案 0 :(得分:1)
使用try
/except
。这是针对您的特定情况的一些伪代码:
for i in range(15,215):
dataset = datasets[i]
# first, try to evaluate your desired code
try:
ANN(dataset)
logistic(dataset)
# if a ValueError occurs, catch it, report on it, and continue
except ValueError as e:
print("Error on dataset {i}: {err}".format(i=i, err=e))
以下是玩具数据的实例:
data = [1, 2, "foo", 3]
for i in range(0,4):
try:
print(int(data[i]))
except ValueError as e:
print("Error on item {i}: {err}".format(i=i, err=e))
输出:
1
2
Error on item 2: invalid literal for int() with base 10: 'foo'
3