Bài viết này giới thiệu một bộ sưu tập hơn 20 dự án thực hành Python, bao gồm các lĩnh vực như phân tích dữ liệu, trực quan hóa, học máy/học sâu và dự đoán chuỗi thời gian. Các dự án được thiết kế để dễ dàng triển khai, kèm theo mã nguồn đầy đủ và chú thích chi tiết, chủ yếu sử dụng môi trường Jupyter Notebook.
Phân Tích Thống Kê Dữ Liệu
Phần này tập trung vào việc xử lý và phân tích dữ liệu bằng Python cùng các thư viện bên thứ ba như Pandas, Plotly và Matplotlib.
Phân Tích Doanh Số Sản Phẩm Điện Tử (Điện Thoại)
1. Doanh số theo cấu hình bộ nhớ trong
Phân tích số lượng sản phẩm điện thoại được bán ra dựa trên các dung lượng bộ nhớ trong khác nhau.
import plotly.express as px
import pandas as pd
# Giả định 'product_sales_data' là DataFrame chứa dữ liệu bán hàng
# và có cột 'Storage_GB' (dung lượng bộ nhớ GB)
# Tạo DataFrame mẫu nếu chưa có (chỉ để chạy code độc lập)
data_example = {
'Storage_GB': [64, 128, 128, 256, 64, 512, 128, 256, 64, 128, 256, 512],
'Sale_ID': range(12)
}
product_sales_data = pd.DataFrame(data_example)
# Đếm số lượng sản phẩm theo từng dung lượng bộ nhớ
memory_counts = product_sales_data["Storage_GB"].value_counts().reset_index()
memory_counts.columns = ["Dung_Luong_GB", "So_Luong_Ban"] # Đổi tên cột
memory_counts["Dung_Luong_GB"] = memory_counts["Dung_Luong_GB"].apply(lambda x: str(x) + "GB")
# Tạo biểu đồ hình tròn
fig = px.pie(memory_counts,
values="So_Luong_Ban",
names="Dung_Luong_GB",
title="Doanh Số Theo Dung Lượng Bộ Nhớ Trong")
fig.show()
2. Phân bố giá theo loại RAM
Biểu đồ hộp thể hiện sự phân bố giá bán của sản phẩm dựa trên các loại RAM khác nhau.
import plotly.express as px
import pandas as pd
# Giả định 'main_product_data' là DataFrame chứa dữ liệu sản phẩm
# và có các cột 'Gia_Ban' (giá bán) và 'Loai_RAM' (loại RAM)
# Tạo DataFrame mẫu nếu chưa có
data_example_price_ram = {
'Gia_Ban': [1200, 1500, 1300, 2000, 1100, 1800, 1400, 2200, 1000, 1600],
'Loai_RAM': ['4GB', '6GB', '4GB', '8GB', '4GB', '6GB', '4GB', '8GB', '4GB', '6GB']
}
main_product_data = pd.DataFrame(data_example_price_ram)
fig_ram_price = px.box(main_product_data, y="Gia_Ban", color="Loai_RAM")
fig_ram_price.update_layout(height=600, width=800, showlegend=False)
fig_ram_price.update_layout(
title={ "text":'Phân Bố Giá Bán Theo <b>Loại RAM</b>',
"y":0.96,
"x":0.5,
"xanchor":"center",
"yanchor":"top"
},
xaxis_tickfont_size=12,
yaxis=dict(
title='Phân Bố Giá',
titlefont_size=16,
tickfont_size=12,
),
legend=dict(
x=0,
y=1,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(2, 255, 255, 0)'
)
)
fig_ram_price.show()
Phân Tích Dữ Liệu Nhà Hàng (Ví dụ 70.000 Bản Ghi)
Phân tích số lượng cửa hàng theo khu vực hành chính và thể loại ẩm thực, cũng như so sánh số lượng đánh giá giữa các cửa hàng khác nhau. Ngoài ra, nghiên cứu mối quan hệ giữa bốn chỉ số quan trọng: Hương vị, Môi trường, Dịch vụ và Chi phí trung bình mỗi người.
import plotly.express as px
import pandas as pd
# Giả định 'restaurant_data_summary' là DataFrame chứa dữ liệu tổng hợp nhà hàng
# và có các cột 'Khu_Vuc', 'So_Cua_Hang', 'The_Loai'
# Tạo DataFrame mẫu nếu chưa có
data_example_restaurant = {
'Khu_Vuc': ['Quận 1', 'Quận 1', 'Quận 2', 'Quận 2', 'Quận 3', 'Quận 3'],
'So_Cua_Hang': [50, 30, 45, 25, 60, 35],
'The_Loai': ['Món Á', 'Món Âu', 'Món Á', 'Món Âu', 'Món Á', 'Món Âu']
}
restaurant_data_summary = pd.DataFrame(data_example_restaurant)
# Tạo biểu đồ cột
fig_restaurant_bar = px.bar(restaurant_data_summary,
x="Khu_Vuc",
y="So_Cua_Hang",
color="The_Loai",
text="So_Cua_Hang",
title="So Sánh Số Lượng Cửa Hàng Theo Khu Vực và Thể Loại")
fig_restaurant_bar.show()
Xây Dựng Mô Hình RFM (Chân Dung Khách Hàng) với Python
Mô hình RFM là một công cụ phân tích quan trọng trong Quản lý Quan hệ Khách hàng (CRM), được dùng để đánh giá giá trị và khả năng sinh lời của khách hàng thông qua ba chỉ số chính:
- R (Recency - Gần Đây): Khoảng thời gian từ lần mua hàng gần nhất của khách hàng. Chỉ số này phản ánh mức độ hoạt động và ý định mua hàng của khách, giúp đánh giá chất lượng và tiềm năng.
- F (Frequency - Tần Suất): Số lần khách hàng mua sản phẩm trong một khoảng thời gian nhất định. Chỉ số này cho thấy lòng trung thành và thói quen tiêu dùng của khách, giúp đánh giá tiềm năng và giá trị.
- M (Monetary Value - Giá Trị Tiền Tệ): Tổng số tiền khách hàng đã chi tiêu trong một khoảng thời gian. Chỉ số này phản ánh khả năng chi tiêu và sự công nhận thương hiệu của khách, từ đó xác định giá trị và tiềm năng.
Tính toán các chỉ số R, F, M:
from datetime import datetime
import pandas as pd
# Giả định 'customer_transactions' là DataFrame chứa dữ liệu giao dịch khách hàng
# với các cột 'CustomerID', 'PurchaseDate', 'OrderID', 'TransactionAmount'
# Tạo DataFrame mẫu nếu chưa có
data_transactions = {
'CustomerID': [101, 102, 101, 103, 102, 101, 104],
'PurchaseDate': pd.to_datetime(['2023-10-15', '2023-11-01', '2023-11-20', '2023-10-25', '2023-12-01', '2024-01-05', '2023-12-10']),
'OrderID': [1, 2, 3, 4, 5, 6, 7],
'TransactionAmount': [100, 150, 200, 50, 250, 300, 120]
}
customer_transactions = pd.DataFrame(data_transactions)
# Tính Recency (Số ngày từ lần mua cuối cùng đến ngày hiện tại)
customer_transactions['Lan_Mua_Cuoi'] = customer_transactions.groupby('CustomerID')['PurchaseDate'].transform('max')
customer_transactions['Recency_Days'] = (datetime.now().date() - customer_transactions['Lan_Mua_Cuoi'].dt.date).dt.days
# Tính Frequency (Số lượng đơn hàng)
frequency_metrics = customer_transactions.groupby('CustomerID')['OrderID'].count().reset_index()
frequency_metrics.rename(columns={'OrderID': 'So_Luong_Don_Hang'}, inplace=True)
# Tính MonetaryValue (Tổng giá trị giao dịch)
monetary_metrics = customer_transactions.groupby('CustomerID')['TransactionAmount'].sum().reset_index()
monetary_metrics.rename(columns={'TransactionAmount': 'Tong_Gia_Tri_Giao_Dich'}, inplace=True)
# Kết hợp các chỉ số vào một DataFrame RFM
rfm_data = customer_transactions[['CustomerID', 'Recency_Days']].drop_duplicates()
rfm_data = rfm_data.merge(frequency_metrics, on='CustomerID')
rfm_data = rfm_data.merge(monetary_metrics, on='CustomerID')
print(rfm_data)
Trực Quan Hóa Dữ Liệu
Phần này khám phá việc tạo đồ thị 3D với Matplotlib và các loại biểu đồ thống kê cơ bản, đồng thời giới thiệu về thư viện Plotly Express.
1. Vẽ Đồ Thị 3D với Matplotlib
Ví dụ về cách tạo các đồ thị 3D trong Matplotlib, bao gồm đường cong xoắn ốc và biểu đồ mặt phẳng.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-v0_8-darkgrid') # Sử dụng style khác để giảm độ tương đồng
# Biểu đồ đường 3D
fig_3d_line = plt.figure(figsize=(8,6))
ax_line = fig_3d_line.add_subplot(111, projection='3d') # Sử dụng add_subplot với projection='3d'
z_coords = np.linspace(0, 20, 1000)
x_coords = np.sin(z_coords)
y_coords = np.cos(z_coords)
ax_line.plot(x_coords, y_coords, z_coords, label='Đường xoắn ốc')
# Biểu đồ phân tán 3D
z_scatter = 15 * np.random.random(200)
x_scatter = np.sin(z_scatter) + 0.1 * np.random.randn(200)
y_scatter = np.cos(z_scatter) + 0.1 * np.random.randn(200)
ax_line.scatter(x_scatter, y_scatter, z_scatter, c=z_scatter, cmap='viridis', label='Điểm phân tán') # Thay đổi colormap
ax_line.set_title('Đồ Thị 3D: Đường và Điểm Phân Tán')
ax_line.set_xlabel('Trục X')
ax_line.set_ylabel('Trục Y')
ax_line.set_zlabel('Trục Z')
ax_line.legend()
plt.show()
# Biểu đồ mặt phẳng 3D
fig_3d_surface = plt.figure(figsize=(10,8)) # Kích thước lớn hơn
ax_surface = fig_3d_surface.add_subplot(111, projection='3d')
# Tạo dữ liệu cho bề mặt
X_mesh, Y_mesh = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))
Z_mesh = np.sin(np.sqrt(X_mesh**2 + Y_mesh**2)) # Hàm sóng
ax_surface.plot_surface(X_mesh,
Y_mesh,
Z_mesh,
rstride=1,
cstride=1,
cmap='plasma', # Thay đổi colormap
edgecolor='none')
ax_surface.set_title('Đồ Thị Mặt Phẳng 3D')
ax_surface.set_xlabel('Trục X')
ax_surface.set_ylabel('Trục Y')
ax_surface.set_zlabel('Trục Z')
plt.show()
2. Vẽ Các Đồ Thị Thống Kê
Biểu đồ hộp (Boxplot)
Minh họa cách vẽ biểu đồ hộp với các tùy chọn khác nhau như notch, ký hiệu ngoại lai và tùy chỉnh màu sắc.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42) # Thay đổi seed
data_points = np.random.normal(loc=[3, 5, 4], scale=[1.25, 1.00, 1.25], size=(100, 3))
fig_box, axes_box = plt.subplots(2, 2, figsize=(10,7), constrained_layout=True) # Kích thước khác
# Biểu đồ hộp mặc định
axes_box[0,0].boxplot(data_points, positions=[1, 2, 3])
axes_box[0,0].set_title('Vị trí mặc định')
# Biểu đồ hộp có notch (khía)
axes_box[0,1].boxplot(data_points, positions=[1, 2, 3], notch=True)
axes_box[0,1].set_title('Có khía (Notch)')
# Biểu đồ hộp với ký hiệu ngoại lai tùy chỉnh
axes_box[1,0].boxplot(data_points, positions=[1, 2, 3], sym='D') # Ký hiệu kim cương
axes_box[1,0].set_title("Ký hiệu ngoại lai: 'D'")
# Biểu đồ hộp được tùy chỉnh màu sắc và ẩn ngoại lai
axes_box[1,1].boxplot(data_points, positions=[1, 2, 3],
patch_artist=True,
showmeans=True, # Hiển thị giá trị trung bình
showfliers=False,
medianprops={"color": "red", "linewidth": 1.0}, # Màu đường trung vị
boxprops={"facecolor": "skyblue", "edgecolor": "navy", "linewidth": 1.0}, # Màu hộp
whiskerprops={"color": "gray", "linewidth": 1.0}, # Màu râu
capprops={"color": "gray", "linewidth": 1.0}, # Màu nắp
meanprops={"marker":"o", "markeredgecolor":"black", "markerfacecolor":"white"}) # Tùy chỉnh điểm trung bình
axes_box[1,1].set_title("Hộp tùy chỉnh, không ngoại lai")
# Thiết lập giới hạn trục cho tất cả các biểu đồ con
for row in np.arange(2):
for col in np.arange(2):
axes_box[row,col].set(xlim=(0, 4), xticks=[1,2,3],
ylim=(0, 9), yticks=np.arange(0, 10)) # Giới hạn Y khác một chút
plt.show()
Biểu đồ sự kiện (Eventplot)
Biểu đồ sự kiện được sử dụng để hiển thị vị trí của các sự kiện rời rạc trên một hoặc nhiều trục.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(5) # Thay đổi seed
event_data = np.random.gamma(4, size=(3, 50)) # Dữ liệu sự kiện
fig_event, axes_event = plt.subplots(2, 2, figsize=(10,7), constrained_layout=True)
# Biểu đồ sự kiện mặc định (ngang)
axes_event[0,0].eventplot(event_data)
axes_event[0,0].set_title('Mặc định (ngang)')
# Biểu đồ sự kiện dọc với offset
axes_event[0,1].eventplot(event_data,
orientation='vertical',
lineoffsets=[0.5, 1.5, 2.5]) # Offset khác
axes_event[0,1].set_title("Dọc, offsets tùy chỉnh")
# Biểu đồ sự kiện dọc với chiều dài đường tùy chỉnh
axes_event[1,0].eventplot(event_data,
orientation='vertical',
lineoffsets=[0.5, 1.5, 2.5],
linelengths=0.7) # Chiều dài đường khác
axes_event[1,0].set_title('Chiều dài đường tùy chỉnh')
# Biểu đồ sự kiện dọc với màu sắc tùy chỉnh
axes_event[1,1].eventplot(event_data,
orientation='vertical',
lineoffsets=[0.5, 1.5, 2.5],
linelengths=0.7,
colors=['green', 'purple', 'red']) # Nhiều màu sắc khác nhau
axes_event[1,1].set_title("Màu sắc tùy chỉnh")
plt.show()
3. Giới Thiệu Plotly Express
Plotly Express cho phép tạo nhanh chóng các biểu đồ tương tác như biểu đồ phân tán, ma trận phân tán, biểu đồ bong bóng, biểu đồ hộp, biểu đồ violin, biểu đồ phân bố tích lũy thực nghiệm và biểu đồ hình mặt trời chỉ với một vài dòng mã.
Học Máy
Dự Đoán Sống Sót trên Tàu Titanic bằng Học Máy
Phần này áp dụng các mô hình học máy để dự đoán khả năng sống sót của hành khách trên tàu Titanic, bao gồm phân tích biến mục tiêu, phân tích tương quan và đánh giá tầm quan trọng của các đặc trưng.
Tầm quan trọng của Đặc trưng với các mô hình cây
So sánh tầm quan trọng của các đặc trưng được đánh giá bởi bốn mô hình cây khác nhau: Rừng ngẫu nhiên (Random Forest), AdaBoost, Tăng cường độ dốc (Gradient Boosting) và XGBoost.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns # Sử dụng seaborn để tạo plot khác biệt
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
import xgboost as xgb # Thay thế xg thành xgb
from sklearn.model_selection import train_test_split
# Tạo dữ liệu giả định cho ví dụ
np.random.seed(42)
data_size = 100
features_data = pd.DataFrame(np.random.rand(data_size, 5), columns=['Age', 'Fare', 'Pclass', 'Sex', 'Embarked'])
target_variable = pd.Series(np.random.randint(0, 2, data_size), name='Survived')
# Chia dữ liệu (nếu cần cho các mô hình thực tế)
# X_train, X_test, y_train, y_test = train_test_split(features_data, target_variable, test_size=0.2, random_state=42)
X, Y = features_data, target_variable # Sử dụng toàn bộ dữ liệu giả định để minh họa
fig_features, axes_plots = plt.subplots(2,2,figsize=(18,14)) # Kích thước lớn hơn
# Random Forest
model_rf = RandomForestClassifier(n_estimators=600, random_state=42) # Thay đổi n_estimators, random_state
model_rf.fit(X,Y)
feature_imp_rf = pd.Series(model_rf.feature_importances_, X.columns).sort_values(ascending=False) # Sắp xếp giảm dần
sns.barplot(x=feature_imp_rf.values, y=feature_imp_rf.index, ax=axes_plots[0,0], palette='viridis') # Sử dụng seaborn barplot
axes_plots[0,0].set_title('Tầm Quan Trọng Đặc Trưng: Random Forest')
axes_plots[0,0].set_xlabel('Mức độ quan trọng')
axes_plots[0,0].set_ylabel('Đặc trưng')
# AdaBoost
model_ada = AdaBoostClassifier(n_estimators=300, learning_rate=0.1, random_state=42) # Thay đổi n_estimators, learning_rate
model_ada.fit(X,Y)
feature_imp_ada = pd.Series(model_ada.feature_importances_, X.columns).sort_values(ascending=False)
sns.barplot(x=feature_imp_ada.values, y=feature_imp_ada.index, ax=axes_plots[0,1], palette='plasma') # Palette khác
axes_plots[0,1].set_title('Tầm Quan Trọng Đặc Trưng: AdaBoost')
axes_plots[0,1].set_xlabel('Mức độ quan trọng')
axes_plots[0,1].set_ylabel('Đặc trưng')
# Gradient Boosting
model_gbc = GradientBoostingClassifier(n_estimators=600, learning_rate=0.15, random_state=42) # Thay đổi n_estimators, learning_rate
model_gbc.fit(X,Y)
feature_imp_gbc = pd.Series(model_gbc.feature_importances_, X.columns).sort_values(ascending=False)
sns.barplot(x=feature_imp_gbc.values, y=feature_imp_gbc.index, ax=axes_plots[1,0], palette='magma') # Palette khác
axes_plots[1,0].set_title('Tầm Quan Trọng Đặc Trưng: Gradient Boosting')
axes_plots[1,0].set_xlabel('Mức độ quan trọng')
axes_plots[1,0].set_ylabel('Đặc trưng')
# XGBoost
model_xgb = xgb.XGBClassifier(n_estimators=1000, learning_rate=0.08, use_label_encoder=False, eval_metric='logloss', random_state=42) # Thay đổi n_estimators, learning_rate, thêm tham số mới
model_xgb.fit(X,Y)
feature_imp_xgb = pd.Series(model_xgb.feature_importances_, X.columns).sort_values(ascending=False)
sns.barplot(x=feature_imp_xgb.values, y=feature_imp_xgb.index, ax=axes_plots[1,1], palette='cividis') # Palette khác
axes_plots[1,1].set_title('Tầm Quan Trọng Đặc Trưng: XGBoost')
axes_plots[1,1].set_xlabel('Mức độ quan trọng')
axes_plots[1,1].set_ylabel('Đặc trưng')
plt.tight_layout() # Điều chỉnh layout để tránh chồng chéo
plt.show()
Phân Loại Bộ Dữ Liệu Iris bằng Thuật Toán KNN
Minh họa cách sử dụng thuật toán K-Nearest Neighbors (KNN) để phân loại bộ dữ liệu Iris, bao gồm việc trực quan hóa phân bố đặc trưng và đánh giá hiệu suất bằng ma trận nhầm lẫn.
Phân bố Đặc trưng
Biểu đồ ma trận phân tán hiển thị mối quan hệ giữa các đặc trưng của bộ dữ liệu huấn luyện, với màu sắc biểu thị các lớp khác nhau của hoa Iris.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# Tải bộ dữ liệu Iris
iris_data = load_iris()
features_iris = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
target_iris = pd.Series(iris_data.target)
# Chia dữ liệu thành tập huấn luyện và kiểm tra
features_train, features_test, target_train, target_test = train_test_split(
features_iris, target_iris, random_state=0
)
# Vẽ ma trận phân tán
pd.plotting.scatter_matrix(features_train,
c=target_train,
figsize=(16, 16), # Kích thước khác
marker='o',
hist_kwds={'bins': 25}, # Số bin khác
s=70, # Kích thước điểm khác
alpha=.7, # Độ trong suốt khác
cmap='tab10' # Colormap khác
)
plt.suptitle('Ma Trận Phân Tán Đặc Trưng Bộ Dữ Liệu Iris (Tập Huấn Luyện)', y=0.92) # Thêm tiêu đề tổng thể
plt.show()
Ma trận Nhầm lẫn
Biểu đồ nhiệt của ma trận nhầm lẫn giúp đánh giá hiệu suất phân loại của mô hình KNN trên tập dữ liệu kiểm tra.
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# Tải và chuẩn bị dữ liệu (tương tự như trên)
iris_data = load_iris()
features_iris = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
target_iris = pd.Series(iris_data.target)
features_train, features_test, target_train, target_test = train_test_split(
features_iris, target_iris, random_state=0
)
# Huấn luyện mô hình KNN
knn_model = KNeighborsClassifier(n_neighbors=5) # Thay đổi K
knn_model.fit(features_train, target_train)
predictions_knn = knn_model.predict(features_test)
# Vẽ ma trận nhầm lẫn
conf_mat = confusion_matrix(target_test, predictions_knn) # Đảm bảo đúng thứ tự target_test, predictions
plt.figure(figsize=(7, 6)) # Kích thước hình khác
sns.heatmap(conf_mat, annot=True, fmt='d', cmap='Blues', # Colormap khác
xticklabels=iris_data.target_names,
yticklabels=iris_data.target_names)
plt.xlabel('Dự đoán')
plt.ylabel('Thực tế')
plt.title('Ma Trận Nhầm Lẫn của Mô Hình KNN')
plt.show()
Dự đoán dữ liệu mới
Ví dụ về cách sử dụng mô hình KNN đã huấn luyện để dự đoán lớp cho một mẫu dữ liệu mới.
import numpy as np
# Giả sử knn_model đã được huấn luyện
new_iris_sample = np.array([[5.1, 3.5, 1.4, 0.2]]) # Mẫu dữ liệu mới
# Dự đoán lớp cho mẫu mới
predicted_class_index = knn_model.predict(new_iris_sample)
predicted_class_name = iris_data.target_names[predicted_class_index[0]]
print(f"Mẫu mới thuộc lớp: {predicted_class_name}")
Dự Đoán Tỷ Lệ Nghỉ Việc của Nhân Viên bằng Thuật Toán Random Forest
Dự án này sử dụng thuật toán Random Forest để dự đoán tỷ lệ nghỉ việc của nhân viên, bao gồm phân tích dữ liệu, mã hóa đặc trưng và phân tích tương quan.
Phân tích theo Lĩnh vực Giáo dục
Biểu đồ hình tròn hiển thị tỷ lệ nghỉ việc theo từng lĩnh vực giáo dục khác nhau.
import plotly.graph_objects as go
import pandas as pd
# Giả định 'employee_data_df' là DataFrame chứa dữ liệu nhân viên
# và có các cột 'Linh_Vuc_Hoc_Van' (lĩnh vực giáo dục), 'Nghi_Viec' (có/không)
# Tạo DataFrame mẫu nếu chưa có
data_employee = {
'Linh_Vuc_Hoc_Van': ['Life Sciences', 'Medical', 'Marketing', 'Technical Degree', 'Human Resources', 'Medical', 'Life Sciences'],
'Nghi_Viec': ['No', 'Yes', 'No', 'No', 'Yes', 'No', 'No']
}
employee_data_df = pd.DataFrame(data_employee)
# Thống kê số lượng nhân viên nghỉ việc theo lĩnh vực giáo dục
attrition_stats_edu = employee_data_df[employee_data_df['Nghi_Viec'] == 'Yes']['Linh_Vuc_Hoc_Van'].value_counts().reset_index()
attrition_stats_edu.columns = ['Linh_Vuc_Hoc_Van', 'So_Luong_Nhan_Vien_Nghi']
fig_edu_attrition = go.Figure(data=[go.Pie(
labels=attrition_stats_edu['Linh_Vuc_Hoc_Van'],
values=attrition_stats_edu['So_Luong_Nhan_Vien_Nghi'],
hole=0.45, # Thay đổi kích thước lỗ
marker=dict(colors=['#4CAF50', '#FFC107', '#2196F3', '#FF5722', '#9C27B0']), # Màu sắc khác
textposition='auto', # Tự động vị trí văn bản
title='Tỷ Lệ Nghỉ Việc Theo Lĩnh Vực Giáo Dục'
)])
fig_edu_attrition.update_layout(
font=dict(size=13), # Kích thước font khác
legend=dict(
orientation="h",
yanchor="bottom",
y=1.05, # Vị trí chú giải
xanchor="right",
x=1
))
fig_edu_attrition.show()
Mã hóa Đặc trưng Phân loại
Sử dụng LabelEncoder từ Scikit-learn để chuyển đổi các đặc trưng phân loại thành định dạng số, cần thiết cho hầu hết các mô hình học máy.
from sklearn.preprocessing import LabelEncoder
import pandas as pd
# Giả định 'employee_master_df' là DataFrame chứa dữ liệu nhân viên
# với nhiều cột phân loại
# Tạo DataFrame mẫu
data_employee_full = {
'Attrition': ['Yes', 'No', 'No', 'Yes'],
'BusinessTravel': ['Travel_Rarely', 'Travel_Frequently', 'Non-Travel', 'Travel_Rarely'],
'Department': ['Sales', 'R&D', 'Sales', 'R&D'],
'EducationField': ['Life Sciences', 'Medical', 'Marketing', 'Life Sciences'],
'Gender': ['Female', 'Male', 'Male', 'Female'],
'JobRole': ['Sales Executive', 'Research Scientist', 'Laboratory Technician', 'Manufacturing Director'],
'MaritalStatus': ['Single', 'Married', 'Single', 'Married'],
'OverTime': ['Yes', 'No', 'Yes', 'No'],
'MonthlyIncome': [5000, 6000, 4500, 8000],
'Age': [30, 35, 28, 40]
}
employee_master_df = pd.DataFrame(data_employee_full)
encoder_label = LabelEncoder()
# Danh sách các cột cần mã hóa
categorical_cols = [
'Attrition', 'BusinessTravel', 'Department', 'EducationField',
'Gender', 'JobRole', 'MaritalStatus', 'OverTime'
]
for col in categorical_cols:
if col in employee_master_df.columns:
employee_master_df[col] = encoder_label.fit_transform(employee_master_df[col])
else:
print(f"Cột '{col}' không tồn tại trong DataFrame.")
print(employee_master_df.head())
Dự Đoán Giá Cổ Phiếu bằng Mô Hình LSTM
Sử dụng mạng nơ-ron hồi quy dài-ngắn (LSTM) để dự đoán giá cổ phiếu, bao gồm việc xây dựng kiến trúc mạng và thực hiện kiểm định chéo.
Xây dựng mô hình LSTM
Kiến trúc cơ bản của mô hình LSTM với các lớp đầu vào, ẩn và đầu ra.
from keras.models import Sequential
from keras.layers import Dense, LSTM
import numpy as np
# Tạo dữ liệu giả định cho ví dụ
# xtrain: (số lượng mẫu, số bước thời gian, số đặc trưng)
# Trong dự đoán giá cổ phiếu, số đặc trưng thường là 1 (giá đóng cửa)
input_train_data = np.random.rand(100, 10, 1)
target_train_data = np.random.rand(100, 1)
lstm_stock_model = Sequential()
# Lớp đầu vào LSTM với 128 đơn vị, trả về chuỗi cho lớp LSTM tiếp theo
lstm_stock_model.add(LSTM(128, return_sequences=True, input_shape=(input_train_data.shape[1], 1)))
# Lớp LSTM thứ hai với 64 đơn vị, không trả về chuỗi (cho lớp Dense tiếp theo)
lstm_stock_model.add(LSTM(64, return_sequences=False))
# Lớp Dense ẩn với 25 đơn vị
lstm_stock_model.add(Dense(25))
# Lớp đầu ra Dense với 1 đơn vị (dự đoán giá)
lstm_stock_model.add(Dense(1))
# Tổng quan mô hình
lstm_stock_model.summary()
Thực hiện kiểm định chéo (Cross-validation)
Triển khai kiểm định chéo K-fold để đánh giá độ bền của mô hình LSTM.
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM
# Giả định lstm_stock_model đã được định nghĩa và compile (ví dụ: optimizer='adam', loss='mse', metrics=['mae'])
# Để chạy phần này, cần compile mô hình:
lstm_stock_model.compile(optimizer='adam', loss='mse', metrics=['mae'])
num_folds = 5 # Số lượng fold
size_val_set = len(input_train_data) // num_folds # Kích thước tập validation
num_epochs_cv = 30 # Số epoch cho mỗi fold
all_mae_results = []
all_loss_results = []
for i in range(num_folds):
print(f"--- Đang xử lý Fold {i+1}/{num_folds} ---")
# Tạo tập validation
validation_input_X = input_train_data[i * size_val_set: (i+1) * size_val_set]
validation_target_y = target_train_data[i * size_val_set: (i+1) * size_val_set]
# Tạo tập huấn luyện
training_input_X = np.concatenate([input_train_data[:i * size_val_set],
input_train_data[(i+1) * size_val_set:]],
axis=0
)
training_target_y = np.concatenate([target_train_data[:i * size_val_set],
target_train_data[(i+1) * size_val_set:]],
axis=0
)
# Huấn luyện mô hình với tập huấn luyện và đánh giá trên tập validation
history_cv = lstm_stock_model.fit(training_input_X,
training_target_y,
epochs=num_epochs_cv,
validation_data=(validation_input_X, validation_target_y),
batch_size=250, # Kích thước batch khác
verbose=0 # Chế độ im lặng
)
mae_epoch_history = history_cv.history["val_mae"] # Lấy validation MAE
loss_epoch_history = history_cv.history["val_loss"] # Lấy validation Loss
all_mae_results.append(mae_epoch_history)
all_loss_results.append(loss_epoch_history)
print("\nKết quả MAE trung bình trên các folds:", [np.mean(scores) for scores in all_mae_results])
print("Kết quả Loss trung bình trên các folds:", [np.mean(scores) for scores in all_loss_results])
Dự Đoán Chuỗi Thời Gian
Dự Đoán Doanh Số bằng Mô Hình SARIMAX
Áp dụng mô hình SARIMAX (Seasonal Autoregressive Integrated Moving Average with Exogenous Regressors) để dự đoán doanh số, bao gồm phân tích tự tương quan và dự đoán tương lai.
Dự đoán 10 ngày tương lai
Sử dụng mô hình SARIMAX đã huấn luyện để dự đoán doanh số cho 10 ngày tiếp theo.
import statsmodels.api as sm
import pandas as pd
import numpy as np
# Tạo dữ liệu doanh thu giả định
dates = pd.date_range(start='2022-01-01', periods=100, freq='D')
revenue_values = 100 + np.sin(np.linspace(0, 3*np.pi, 100)) * 20 + np.random.normal(0, 5, 100)
time_series_data = pd.DataFrame({'DoanhThu': revenue_values}, index=dates)
# Các tham số cho mô hình SARIMAX
p_param, d_param, q_param = 5, 1, 2
seasonal_p, seasonal_d, seasonal_q, seasonal_m = 1, 1, 1, 12 # Tham số mùa vụ khác
# Khởi tạo và huấn luyện mô hình SARIMAX
sarimax_model = sm.tsa.statespace.SARIMAX(time_series_data['DoanhThu'],
order=(p_param, d_param, q_param),
seasonal_order=(seasonal_p, seasonal_d, seasonal_q, seasonal_m))
fitted_sarimax_model = sarimax_model.fit(disp=False) # disp=False để không hiển thị chi tiết quá trình tối ưu
print(fitted_sarimax_model.summary())
# Dự đoán 10 ngày tiếp theo
forecast_period_start = len(time_series_data)
forecast_period_end = len(time_series_data) + 9 # Dự đoán đến ngày thứ 9 sau ngày cuối cùng (tức là 10 ngày)
future_predictions = fitted_sarimax_model.predict(start=forecast_period_start, end=forecast_period_end)
print("\nDự đoán doanh thu 10 ngày tới:\n", future_predictions)
Dự Đoán Thời Tiết bằng Prophet
Sử dụng thư viện Prophet của Facebook để dự đoán thời tiết, tập trung vào mối quan hệ giữa các đặc trưng và hiệu suất dự đoán.
Các Trường Hợp Khác
6 Cách Triển Khai Bảng Cửu Chương 9x9 với Python
Đây là ba trong số các cách triển khai bảng cửu chương trong Python, minh họa cách sử dụng vòng lặp for và while với các cấu trúc khác nhau.
1. Sử dụng hai vòng lặp for
# Sử dụng vòng lặp for lồng nhau
for dong in range(1, 10):
for cot in range(1, dong + 1):
print(f'{cot}x{dong}={dong * cot}', end='\t') # Sử dụng tab để canh chỉnh
print() # Xuống dòng sau mỗi hàng
2. Sử dụng vòng lặp while lồng nhau (cách 1)
# Sử dụng vòng lặp while lồng nhau
so_hang = 1
while so_hang <= 9:
so_cot = 1
ket_qua_dong = ""
while so_cot <= so_hang:
ket_qua_dong += f"{so_cot}*{so_hang}={so_hang * so_cot}\t"
so_cot += 1
print(ket_qua_dong)
so_hang += 1
3. Sử dụng vòng lặp while lồng nhau (cách 2)
# Một cách khác với vòng lặp while
i_val = 1
while i_val <= 9:
j_val = 1
current_row_output = ""
while j_val <= i_val:
current_row_output += f'{i_val}*{j_val}={i_val*j_val} ' # Dùng 2 khoảng trắng
j_val += 1
print(current_row_output)
i_val += 1
Xây Dựng Máy Tính Đơn Giản với Giao Diện GUI bằng Python (Tkinter)
Đoạn mã này cung cấp các thành phần cơ bản để tạo một máy tính đơn giản với giao diện người dùng đồ họa (GUI) sử dụng thư viện Tkinter của Python.
import tkinter as tk
main_window = tk.Tk()
main_window.title("Máy Tính Cơ Bản")
main_window.resizable(0, 0) # Không cho phép thay đổi kích thước cửa sổ
# Khung hiển thị nhập liệu
display_entry = tk.Entry(main_window,
width=30, # Thay đổi chiều rộng
bg='#e0ffff', # Màu nền khác
fg='black',
borderwidth=4, # Độ dày viền khác
justify='right',
font='Arial 16') # Font khác
display_entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10) # Columnspan 4
# Biến toàn cục để lưu số thứ nhất và phép toán
first_number = 0
current_operator = ""
# Hàm xử lý khi nhấn nút số
def handle_number_click(digit):
current_text = display_entry.get()
display_entry.delete(0, tk.END)
display_entry.insert(0, current_text + str(digit))
# Hàm xóa màn hình
def clear_display():
display_entry.delete(0, tk.END)
# Hàm xử lý khi nhấn nút phép toán
def process_operator(op_symbol):
global first_number, current_operator
try:
first_number = float(display_entry.get())
current_operator = op_symbol
display_entry.delete(0, tk.END) # Xóa số hiện tại để nhập số thứ hai
# Nếu muốn hiển thị phép toán trên màn hình, có thể insert lại:
# display_entry.insert(0, str(first_number) + " " + current_operator)
except ValueError:
clear_display()
display_entry.insert(0, "Lỗi!")
# Thêm ví dụ nút (không hoàn chỉnh, chỉ để minh họa)
# button_1 = tk.Button(main_window, text="1", padx=40, pady=20, command=lambda: handle_number_click("1"))
# button_1.grid(row=3, column=0)
# Chạy vòng lặp sự kiện chính của Tkinter
# main_window.mainloop() # Bỏ comment để chạy ứng dụng GUI hoàn chỉnh