Python tips cool
Một số tricks cơ bản trong python
Lambda, map, filter, reduce
Sử dụng lambda
1
2
3
4
5
6
7
| def fn(x): #x^2
return x ** 2
ld = lambda x : x * x #su dung lambda (1 arg x)
for i in range(10):
assert fn(i) == ld(i)
|
Sử dụng map để callbacks qua hàm khác
1
2
3
4
5
6
7
8
9
10
11
12
| numbers = [1/3, 2/3, 123/234, 89/87]
numbers_sq = [x * x for x in numbers]
print(numbers_sq)
# use map (callback)
numbers_sq1 = map(fn, numbers)
numbers_sq2 = map(ld, numbers)
numbers_sq3 = map(lambda x: x ** 2, numbers)
print(list(numbers_sq1))
print(list(numbers_sq2))
print(list(numbers_sq3))
|
Tính MSE (mean squared error)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # tinh MSE (mean squared error) f(x) = ax + b
a, b = 3, -0.5
xs = [2, 3, 4, 5]
labels = [6.4, 8.9, 10.9, 15.3]
#using a loop
errors = []
for i, x in enumerate(xs):
errors.append((a * x + b - labels[i]) ** 2)
results1 = sum(errors) ** 0.5 / len(xs)
#using map
diffs = map(lambda x, y : (a * x + b - y) ** 2, xs, labels)
results2 = sum(diffs) ** 0.5 / len(xs)
print(results1, results2)
|
Sử dụng filter để chọn giá trị
1
2
3
| # using filter de chon gia tri
bad_preds = filter(lambda x : x > 0.5, errors)
print(list(bad_preds))
|
Sử dụng reduce áp dụng vào elements của list
1
2
3
4
5
6
7
8
9
10
11
| # use reduce if you want apply an operator to all elements in a list
numbers = [1/3, 2/3, 123/234, 89/87]
# use loop
product = 1
for n in numbers:
product *= n
#use reduce
from functools import reduce
product1 = reduce(lambda x, y: x * y, numbers)
print(product, product1)
|
List Manipulation
Unpacking
1
2
3
4
5
6
| #unpacking
elems = [1, 2, 3, 4]
a, b, c, d = elems
print(a, b, c, d)
a, *new_elems, d = elems # na na contro C++
print(a, new_elems, d)
|
Slicing
1
2
3
4
5
6
7
8
| #slicing
elems = list(range(10))
print(elems)
print(elems[::-2]) # duyet tu cuoi ve
print(elems[::2]) # duyet tu dau di
#delete
del elems[::3]
print(elems)
|
Insertion
1
2
3
4
5
6
7
8
9
10
11
12
| #insertion
elems = list(range(10))
elems[1] = 10
print(elems)
elems = list(range(10))
elems[1:2] = [20, 30, 40, 50] #replace value 1 bang 4 value khac.
print(elems)
elems = list(range(10))
elems[1:1] = [0.2, 0.3, 0.4, 0.5]
print(elems) # insert 4 value vao index (0, 1)
|
Flattening
1
2
3
| #flattening
list_of_lists = [[1], [3, 4], [5, 4, 3]]
sum(list_of_lists, [])
|
List and Generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| #list and generator
# create n-grams
tokens = ['i', 'want', 'to', 'go', 'to', 'school']
def ngrams(tokens, n): #O(m * n)
length = len(tokens)
grams = []
for i in range(length - n + 1):
grams.append(tokens[i:i+n])
return grams
ngrams(tokens, 3)
print('------')
def ngrams(tokens, n):
length = len(tokens)
for i in range(length - n + 1):
yield tokens[i:i+n]
ngrams_generator = ngrams(tokens, 3)
print(ngrams_generator)
for x in ngrams_generator:
print(x)
print('------')
def ngrams(tokens, n):
length = len(tokens)
slices = (tokens[i:length - n + 1 + i] for i in range(n))
return zip(*slices)
ngrams_generator = ngrams(tokens, 3)
print(ngrams_generator)
for x in ngrams_generator:
print(x)
|
Classes and magic methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| # __repr__ (print value object)
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
strings = [f'value: {self.value}']
strings.append(f'left: {self.left.value}' if self.left else 'left: None')
strings.append(f'right: {self.right.value}' if self.right else 'right: None')
return ', '.join(strings)
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
def __ge__(self, other):
return self.value > other.value
left = Node(4)
right = Node(6)
root = Node(5, left, right)
print(root)
print(left)
print(right)
print(left == root)
print(left < root)
print(left >= root)
|
Local namespace, object attributes
1
2
3
4
5
6
7
8
| class Model:
def __init__(self, **kwargs):
self.__dict__ = kwargs
m = Model(hidden_size = 100, num_layers = 3, learning_rate = 3e-4)
print(m.__dict__)
print(m.__dict__['learning_rate'])
print(m.__dict__['num_layers'])
print(m.__dict__['hidden_size'])
|
Link tham khảo
Full ipynb
Tài liệu tham khảo
Machine learning cơ bản
Hết.