Step 4: Accuracy چالش 4 از جلسهی 12، سخت
لیست tests عکسهای تازه با برچسب درست دارد. هر کدام را با recognise تشخیص بده، چاپ کن guess 1 real 1 ok یا ... wrong، و در پایان accuracy: 4 of 4.
def flatten(picture):
return [1 if ch == "#" else 0 for row in picture for ch in row]
def distance(a, b):
return sum(1 for i in range(len(a)) if a[i] != b[i])
training = [
([".#####.", "#.....#", "#.....#", "#.....#", "#.....#", "#.....#", ".#####."], 0),
(["..###..", ".#...#.", "#.....#", "#.....#", "#.....#", ".#...#.", "..###.."], 0),
([".####..", "#....#.", "#....#.", "#....#.", "#....#.", "#....#.", ".####.."], 0),
(["...#...", "..##...", "...#...", "...#...", "...#...", "...#...", ".#####."], 1),
(["...#...", "...#...", "...#...", "...#...", "...#...", "...#...", "...#..."], 1),
(["..#....", ".##....", "..#....", "..#....", "..#....", "..#....", ".####.."], 1),
]
tests = [
(["...#...", "..##...", "...#...", "...#...", "...#...", "...#...", "..###.."], 1),
([".#####.", "#.....#", "#.....#", "#..#..#", "#.....#", "#.....#", ".#####."], 0),
(["....#..", "...##..", "....#..", "....#..", "....#..", "....#..", "..####."], 1),
(["..####.", ".#....#", ".#....#", ".#....#", ".#....#", ".#....#", "..####."], 0),
]
def recognise(picture):
pixels = flatten(picture)
scored = []
for p, label in training:
scored.append((distance(pixels, flatten(p)), label))
scored.sort()
votes = {}
for d, label in scored[:3]:
votes[label] = votes.get(label, 0) + 1
return max(votes, key=votes.get)
correct = 0
راهنما و جواب این چالش · برگشت به درس جلسهی 12: پروژه: تشخیص رقم کوچک
بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد