Diễn đàn python

Diễn đàn python

Share

Trao đổi và giảng dạy python diễn đàn về học và lập trình python

14/02/2025

Có mấy phép nhân ma trận trong thư viện Numpy bạn hay dùng?
- Phép nhân từng phần tử *
- Phép nhân ma trận thông thường (nhân hàng với cột) .dot
- Phép nhân ngoài outer.

14/02/2025

Trong mạng RNN, hiểu rõ BackPropagation Through Time (BPTT) khá là khó ... Cơn ác mộng của sausage man.

14/02/2025

Lập trình viên Python luôn thích rủ rê!

30/05/2023

Muốn khởi tạo một khối dữ liệu (có thể là 1 số (scalar), 1 véc-tơ (1 chiều), 1 ma trận (2 chiều) hoặc tensor(3) chiều), có thể dùng các lệnh trong numpy. Ví dụ khởi tạo ma trận 3 x 4 (3 hàng, 4 cột) gồm toàn số 0:
import numpy as np
a = np.zeros((3, 4))
Bạn lưu ý là phải khai báo kích thước của khối dữ liệu bằng một tuple, như ở trên là (3, 4) để chỉ 3 hàng và 4 cột. Muốn tạo khối b có kích thước như khối a, nhưng lại gồm toàn số 1, ta làm như sau:
b = np.ones(a.shape)
Muốn tạo ngẫu nhiên các giá trị cho khối dữ liệu. Chẳng hạn tạo một tensor 3x2x5 mà mỗi phần tử có giá trị là một số ngẫu nhiêu tuân theo luật phân phối đều trong khoảng [0,5, 0,9] nghĩa là các giá trị lấy ngẫu nhiên lớn hơn 0,5 và bé hơn 0,9, ta làm như sau:
c = np.random.uniform(0.5, 0.9, (3, 2, 5))

24/05/2023

Đôi khi ta chỉ cần một phần thông tin trả về của một hàm nào đó, ta có thể gán phần thông tin không cần thiết cho biến _. Trong ví dụ sau, hàm sum_difference(a, b) trả về tổng và hiệu của a và b, cụ thể là a + b và a - b. Ta chỉ quan tâm đến tổng của a và b mà thôi.

def sum_difference(a, b):
return a + b, a - b

sum, _ = sum_difference(a, b)

data-science-mini-course - Google Drive 23/05/2023

Bài hồi quy tuyến tính (linear regression) với dữ liệu về kích thước - khối lượng của các mẫu cá, và mục tiêu là dự đoán khối lượng của cá dựa vào các kích thước. Đây là link có chứa tệp hướng dẫn và mã nguồn sử dụng. Để dùng mã nguồn, bạn chỉ cần thay đường link chỉ đến để data của bạn.

data-science-mini-course - Google Drive

GitHub - maciejbalawejder/Reinforcement-Learning-Collection 23/05/2023

Ví dụ đầu tiên với Reinforcement Learning (RL) sử dụng thư viện Gym của OpenAI. Mình tham khảo 99% từ nguồn này: https://medium.com/analytics-vidhya/q-learning-is-the-most-basic-form-of-reinforcement-learning-which-doesnt-take-advantage-of-any-8944e02570c5
Tuy vậy, hiện tại Gym có phiên bản 0.26.* khiến một số dòng lệnh trên ví dụ này chạy bị lỗi (nó chạy bình thường trên Gym phiên bản 0.25.*), mình có sửa lại và ghi chú những chỗ cần sửa cho từng phiên bản trong mã nguồn đính kèm:
import gym
import numpy as np
import matplotlib.pyplot as plt
import time

# Description: CartPole problem aims to control a pole so as to keep the pole balanced \
# vertically on a cart. The given information is the position, the velocity of the cart \
# , the angle of the pole, and the rotational rate of the pole. The agent can make a force \
# on the left or right of the cart. If the pole falls more than 15 degrees from vertical, \
# game is over.
# Source: https://github.com/maciejbalawejder/Reinforcement-Learning-Collection/blob/main/Q-Table/Qtable.ipynb

# Define CART POLE
env = gym.make('CartPole-v1', render_mode = "human")
print(env.observation_space.low, "\n")

def Qtable(state_space, action_space, bin_size = 30):
bins = [np.linspace(-4.8, 4.8, bin_size),
np.linspace(-4, 4, bin_size),
np.linspace(-0.418, 0.418, bin_size),
np.linspace(-4, 4, bin_size)]
q_table = np.random.uniform(low = -1, high = 1, size = ([bin_size] * state_space\
+ [action_space]))
return q_table, bins

def Discrete(state, bins):
index = []
for i in range(len(state)):
index.append(np.digitize(state[i], bins[i], right=False) - 1)
return tuple(index)

def Q_learning(q_table, bins, episodes = 5000, gamma = 0.95, lr = 0.1, timestep = 100, \
epsilon = 0.2):
rewards = 0
solved = False
steps = 0
runs = [0]
data = {'max': [0], 'avg': [0]}
start = time.time()
ep = [i for i in range(0, episodes + 1, timestep)]

for episode in range(1, episodes + 1):
current_state = Discrete(env.reset(), bins) # initial observation
# current_state = Discrete(env.reset()[0], bins) # for gym v. 0.26.*
score = 0
done = False
temp_start = time.time()

while not done:
steps += 1
ep_start = time.time()
if episode % timestep == 0:
env.render()

if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample()
else:
action = np.argmax(q_table[current_state])

observation, reward, done, info = env.step(action)
# observation, reward, done, info, _ = env.step(action) # for gym v. 0.26.*
next_state = Discrete(observation, bins)

score += reward

if not done:
max_future_q = np.max(q_table[next_state])
current_q = q_table[current_state + (action, )]
new_q = (1 - lr) * current_q + lr * (reward + gamma * max_future_q)
q_table[current_state + (action, )] = new_q

current_state = next_state

# End of loop update
else:
rewards += score
runs.append(score)
if score > 195 and steps >= 100 and solved == False: # considered as a solved:
solved = True
print('Solved in episode : {} in time {}'.format(episode, (time.time() - ep_start)))

# Timestep value update
if episode % timestep == 0:
print('Episode : {} | Reward -> {} | Max reward: {} | Time : {}'.\
format(episode, rewards/timestep, max(runs), time.time() - ep_start))
data['max'].append(max(runs))
data['avg'].append(rewards/timestep)
if rewards/timestep >= 195:
print('Solved in episode: {}'.format(episode))
rewards, runs = 0, [0]

if len(ep) == len(data['max']):
plt.plot(ep, data['max'], label = 'Max')
plt.plot(ep, data['avg'], label = 'Avg')
plt.xlabel('Episode')
plt.ylabel('Reward')
plt.legend(loc = 'upper left')
plt.show()

env.close()

# Training
q_table, bins = Qtable(len(env.observation_space.low), env.action_space.n)
Q_learning(q_table, bins, lr = 0.15, gamma = 0.995, episodes = 5000, timestep = 1000)

GitHub - maciejbalawejder/Reinforcement-Learning-Collection Contribute to maciejbalawejder/Reinforcement-Learning-Collection development by creating an account on GitHub.

Q-Learning is the most basic form of Reinforcement Learning, which doesn’t take advantage of any… 23/05/2023

Ví dụ đầu tiên với Reinforcement Learning (RL) sử dụng thư viện Gym của OpenAI. Mình tham khảo 99% từ nguồn này: https://medium.com/analytics-vidhya/q-learning-is-the-most-basic-form-of-reinforcement-learning-which-doesnt-take-advantage-of-any-8944e02570c5
Tuy vậy, hiện tại Gym có phiên bản 0.26.* khiến một số dòng lệnh trên ví dụ này chạy bị lỗi (nó chạy bình thường trên Gym phiên bản 0.25.*), mình có sửa lại và ghi chú những chỗ cần sửa cho từng phiên bản trong mã nguồn đính kèm:
import gym
import numpy as np
import matplotlib.pyplot as plt
import time

# Description: CartPole problem aims to control a pole so as to keep the pole balanced \
# vertically on a cart. The given information is the position, the velocity of the cart \
# , the angle of the pole, and the rotational rate of the pole. The agent can make a force \
# on the left or right of the cart. If the pole falls more than 15 degrees from vertical, \
# game is over.
# Source: https://github.com/maciejbalawejder/Reinforcement-Learning-Collection/blob/main/Q-Table/Qtable.ipynb

# Define CART POLE
env = gym.make('CartPole-v1', render_mode = "human")
print(env.observation_space.low, "\n")

def Qtable(state_space, action_space, bin_size = 30):
bins = [np.linspace(-4.8, 4.8, bin_size),
np.linspace(-4, 4, bin_size),
np.linspace(-0.418, 0.418, bin_size),
np.linspace(-4, 4, bin_size)]
q_table = np.random.uniform(low = -1, high = 1, size = ([bin_size] * state_space\
+ [action_space]))
return q_table, bins

def Discrete(state, bins):
index = []
for i in range(len(state)):
index.append(np.digitize(state[i], bins[i], right=False) - 1)
return tuple(index)

def Q_learning(q_table, bins, episodes = 5000, gamma = 0.95, lr = 0.1, timestep = 100, \
epsilon = 0.2):
rewards = 0
solved = False
steps = 0
runs = [0]
data = {'max': [0], 'avg': [0]}
start = time.time()
ep = [i for i in range(0, episodes + 1, timestep)]

for episode in range(1, episodes + 1):
current_state = Discrete(env.reset(), bins) # initial observation
# current_state = Discrete(env.reset()[0], bins) # for gym v. 0.26.*
score = 0
done = False
temp_start = time.time()

while not done:
steps += 1
ep_start = time.time()
if episode % timestep == 0:
env.render()

if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample()
else:
action = np.argmax(q_table[current_state])

observation, reward, done, info = env.step(action)
# observation, reward, done, info, _ = env.step(action) # for gym v. 0.26.*
next_state = Discrete(observation, bins)

score += reward

if not done:
max_future_q = np.max(q_table[next_state])
current_q = q_table[current_state + (action, )]
new_q = (1 - lr) * current_q + lr * (reward + gamma * max_future_q)
q_table[current_state + (action, )] = new_q

current_state = next_state

# End of loop update
else:
rewards += score
runs.append(score)
if score > 195 and steps >= 100 and solved == False: # considered as a solved:
solved = True
print('Solved in episode : {} in time {}'.format(episode, (time.time() - ep_start)))

# Timestep value update
if episode % timestep == 0:
print('Episode : {} | Reward -> {} | Max reward: {} | Time : {}'.\
format(episode, rewards/timestep, max(runs), time.time() - ep_start))
data['max'].append(max(runs))
data['avg'].append(rewards/timestep)
if rewards/timestep >= 195:
print('Solved in episode: {}'.format(episode))
rewards, runs = 0, [0]

if len(ep) == len(data['max']):
plt.plot(ep, data['max'], label = 'Max')
plt.plot(ep, data['avg'], label = 'Avg')
plt.xlabel('Episode')
plt.ylabel('Reward')
plt.legend(loc = 'upper left')
plt.show()

env.close()

# Training
q_table, bins = Qtable(len(env.observation_space.low), env.action_space.n)
Q_learning(q_table, bins, lr = 0.15, gamma = 0.995, episodes = 5000, timestep = 1000)

Q-Learning is the most basic form of Reinforcement Learning, which doesn’t take advantage of any… Background information

20/06/2022

Thực sự, tuy Python tốc độ thực thi thua kém so với C++ nhưng nó lại làm thay bạn rất nhiều việc. Khi bạn khởi tạo một danh sách cục bộ rồi thoát ra, Python tự động dọn dẹp phần bộ nhớ cấp phát cho danh sách đó. Nhưng với C++, bạn phải tự mình thực hiện với lệnh delete.

01/11/2021

Bạn có biết?

OpenCV (Open Source Computer Vision) là một thư viện xử lý ảnh và video. Ban đầu, nó được Intel phát triển vào tháng sáu năm 2020 nhưng sau đó được Willow Garage phụ trách và hiện tại (2021) là Itseez. Đây là một thư viện miễn phí và mở áp dụng giấy phép open-source Apache 2.

Thư viện này đa nền tảng được viết bằng C++ nhưng có thể sử dụng trong nhiều ngôn ngữ khác như Python, Java, MATLAB/OCTAVE và thậm chí là JavaScript.

Ví dụ kiểu 'hellow world': đọc một bức ảnh ta khai báo thư viện cv2, đọc ảnh định dạng RGB và bật lại ảnh:

import cv2

img = cv2.imread("abc.png")
cv2.imshow('image', img)

Want your school to be the top-listed School/college in Hanoi?

Click here to claim your Sponsored Listing.

Location

Category

Telephone

Address


Hanoi
100000