Buoi3_datamining_TieuAnhHuy_110122007
April 19, 2025
[ ]:importpandasaspd
importnumpyasnp
importseabornassns
importmatplotlib.pyplotasplt
df=pd.read_csv('train.csv')
[ ]:df.head()
[ ]:df.shape
[ ]:#Thống kê mô tả dữ liệu:
df.info()
[ ]:#Thống kê mô tả dữ liệu:
print("\nThống kê mô tả dữ liệu:")
print(df.info())
[ ]:# Đếm số lượng giá trị thiếu:
print("\nSố lượng giá trị thiếu:")
print(df.isnull().sum())
[ ]:# Tính tỷ lệ phần trăm giá trị thiếu:
print("\nTỷ lệ giá trị thiếu:")
print(df.isnull().mean()*100)
[ ]:# Trực quan hóa bằng heatmap:
print("\nTrực quan hóa bằng heatmap:")
sns.heatmap(df.isnull(), cbar=False, cmap='viridis')#cbar = False de khong hien
plt.show()
[ ]:importpandasaspd
fromscipy.statsimportskew
# Giả sử df là DataFrame chứa dữ liệu Titanic
# Kiểm tra skewness cho cột 'Age'
age_skewness=skew(df['Age'].dropna())# Loại bỏ giá trị NaN trước khi tính t
print(f"Hệ số skewness của cột'Age':{age_skewness}")
# Quyết định sử dụng mean hay median dựa trên skewness
ifabs(age_skewness)>1:# Ngưỡng phổ biến để xác định phân bố lệch
1
print("Phân bố lệch mạnh. Sử dụng median để điền giá trị thiếu.")
else:
print("Phân bố gần đối xứng. Có thể sử dụng mean để điền giá trị thiếu.")
[ ]:# Điền Age:
df['Age']=df.groupby(['Pclass','Sex'])['Age'].transform(lambdax: x.fillna(x.
↪mean()))
df.info()
[ ]:#đã loại bỏ Cabin
[ ]:# Điền Embarked:
df['Embarked']=df['Embarked'].fillna(df['Embarked'].mode()[0])
# Kiểm tra lại:
print("\nThống kê dữ liệu missing:")
print(df.isnull().sum())
[ ]:# Kiểm tra thống kê mô tả
print(df.describe())
[ ]:importseabornassns
importmatplotlib.pyplotasplt
# Boxplot cho Fare và Age
plt.figure(figsize=(12,6))
plt.subplot(1,2,1)
sns.boxplot(y=df['Fare'])
plt.title('Boxplot of Fare')
plt.subplot(1,2,2)
sns.boxplot(y=df['Age'])
plt.title('Boxplot of Age')
plt.show()
[ ]:# Histogram cho Fare và Age
plt.figure(figsize=(12,6))
plt.subplot(1,2,1)
sns.histplot(df['Fare'], bins=30, kde=True)
plt.title('Histogram of Fare')
plt.subplot(1,2,2)
sns.histplot(df['Age'].dropna(), bins=30, kde=True)
plt.title('Histogram of Age')
plt.show()
[ ]:# Scatter plot giữa Age và Fare
plt.figure(figsize=(8,6))
sns.scatterplot(x='Age', y='Fare', data=df)
plt.title('Scatter Plot of Age vs Fare')
plt.show()
2
[ ]:#Kiểm tra giá trị âm:
if(df['Fare']<0).any():
print("Có giá trị âm trong cột Fare!")
Q1=df['Fare'].quantile(0.25)
Q3=df['Fare'].quantile(0.75)
IQR=Q3-Q1
# Giới hạn trên và dưới
lower_bound=Q1-1.5*IQR
upper_bound=Q3+1.5*IQR
# Lọc dữ liệu
df=df[(df['Fare']>=lower_bound)&(df['Fare']<=upper_bound)]
[ ]:if(df['Age']<0).any():
print("Có giá trị âm trong cột Age!")
Q1=df['Age'].quantile(0.25)
Q3=df['Age'].quantile(0.75)
IQR=Q3-Q1
# Giới hạn trên và dưới
lower_bound=Q1-1.5*IQR
upper_bound=Q3+1.5*IQR
# Lọc dữ liệu
df=df[(df['Age']>=lower_bound)&(df['Age']<=upper_bound)]
[ ]:# Loại bỏ các cột 'Name' và 'Ticket'
df=df.drop(columns=['Name','Ticket'])
print(df.head())# In 5 dòng đầu tiên print(df.dtypes) # Kiểm tra kiểu dữ␣
↪liệu của các cột còn lại
[ ]:sns.boxplot(x=df['Fare'])# Hoặc y='Fare', data=df plt.show()
[ ]:Q1=df['Fare'].quantile(0.25)
Q3=df['Fare'].quantile(0.75)
IQR=Q3-Q1
lower_bound=Q1-1.5*IQR
upper_bound=Q3+1.5*IQR
outliers=df[(df['Fare']<lower_bound)|(df['Fare']>upper_bound)]
print(outliers)
[ ]:df['Sex']=df['Sex'].replace({'male':'Male','female':'Female'})
df['Embarked']=df['Embarked'].replace({'S':'Southampton','C':'Cherbourg',␣
↪'Q':'Queenstown'})
df.head()
[ ]:# Số bản ghi trùng
df.duplicated().sum()
# Xem các bản ghi trùng
3
df[df.duplicated()]
[ ]:# Xóa bản ghi trùng
df.drop_duplicates(inplace=True)
[ ]:fromsklearn.preprocessingimportLabelEncoder
print(df.head())
# Khởi tạo Label Encoder
label_encoders={}
forcolin['Sex','Embarked']:
le=LabelEncoder()
df[col]=le.fit_transform(df[col].astype(str))
# Chuyển NaN thành chuỗi n
label_encoders[col]=le
# Lưu lại encoder để sử dụng sau (nếu cần)
# Kiểm tra kết quả
print(df[['Sex','Embarked']].head())
[ ]:# Áp dụng One-Hot Encoding cho các cột chuỗi
#df = pd.get_dummies(df, columns=['Sex', 'Embarked'], drop_first=True)
# Kiểm tra kết quả
print(df.head())
[ ]:# Tính ma trận tương quan
correlation_matrix=df.corr()
# Vẽ heatmap để trực quan hóa tương quan
plt.figure(figsize=(10,8))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f')
plt.title('Heatmap of Correlation Matrix')
plt.show()
[ ]:# Vẽ biểu đồ boxplot để kiểm tra mối quan hệ giữa 'Pclass' và 'Survived'
plt.figure(figsize=(8,6))
sns.boxplot(x='Pclass', y='Survived', data=df)
plt.title('Boxplot of Pclass vs Survived')
plt.show()
[ ]:# Loại bỏ cột 'Fare' nếu nó có tương quan cao với 'Pclass'
df=df.drop(columns=['Fare'])
4