ABC 부트캠프 데이터 탐험가 4기

[18 일차] ABC 부트캠프 : 머신러닝 (1) Code01~Code02

marriina 2024. 7. 31. 11:06

파이썬 주요 라이브러리

 

https://www.jetbrains.com/
jetbrains 에서 pycharm 설치 

설치 후, settings -> project:  -> Python interpreter -> + 버튼 으로 라이브러리 설치
Beautifulsoup4 , matplotlib, numpy, pandas , scikit-learn , tensorflow 등 설치 

설치된 라이브러리들


Code01

import numpy as np  # numpy 라이브러리를 np라는 이름으로 임포트

# 파스칼 노테이션으로 ndarray 생성
a:np.ndarray = np.array(object=[1,2,3])  # 1, 2, 3으로 이루어진 numpy 배열 생성
print(a)  # 배열 a 출력
print(type(a))  # 배열 a의 타입 출력

b= np.array([1,2,3,4,5,6,7.0,8,9,10])  # 다양한 숫자로 이루어진 배열 생성
print(b)  # 배열 b 출력
print(type(b))  # 배열 b의 타입 출력

# 행렬 초기화
c = np.zeros(shape=(3,4))  # 3x4 크기의 모든 원소가 0인 배열 생성
print(f'NP.ZEROS : \n{c}')  # c 배열 출력

print(a[0])  # 배열 a의 첫 번째 원소 출력
print(a[1])  # 배열 a의 두 번째 원소 출력

print(c[0][0])  # c 배열의 첫 번째 행, 첫 번째 열 원소 출력
print(c[0,0])  # c 배열의 첫 번째 행, 첫 번째 열 원소 출력 (다른 접근 방법)

d = np.ones((4,4))  # 4x4 크기의 모든 원소가 1인 배열 생성
print(d)  # d 배열 출력

result = np.arange(start=0,stop= 6,step=1)  # 0부터 5까지의 정수 배열 생성
print(result)  # result 배열 출력
print(np.linspace(start=0, stop=10,num=100))  # 0부터 10까지 100개의 균등한 점 생성

np_array = np.array([2, 1, 5, 3, 7, 4, 6, 8,])  # 정수 배열 생성
print(np_array)  # np_array 출력
print(np.sort(np_array))  # np_array를 정렬하여 출력
print(np_array)  # np_array 출력 (변경되지 않음)
np_array_sorting = np.sort(np_array)  # np_array를 정렬하여 새로운 배열에 저장
print(np_array_sorting)  # 정렬된 배열 출력

x1 = np.array([[1, 2, ], [3, 4, ]])  # 2x2 배열 x1 생성
y1 = np.array([[5, 6, ], [7, 8, ]])  # 2x2 배열 y1 생성
result = np.concatenate([x1, y1], axis=0)  # x1과 y1을 세로로 연결
print(result)  # 연결된 결과 출력

print('-----------------------------')  
x2 = np.array([[1, 2, ], [3, 4, ]])  # 2x2 배열 x2 생성
y2 = np.array([[5, 6, ], [7, 8, ]])  # 2x2 배열 y2 생성
result2 = np.concatenate([x2, y2], axis=1)  # x2와 y2를 가로로 연결
print(result2)  # 연결된 결과 출력
print('-----------------------------')  
array_1 = np.arange(12)  # 0부터 11까지의 정수 배열 생성
print(array_1)  # array_1 출력
print(array_1.reshape(3,4))  # array_1을 3x4 배열로 재구성하여 출력
print('-----------------------------')  
print(array_1.reshape(4,3))  # array_1을 4x3 배열로 재구성하여 출력

print('-----------------------------')  
# 차원 증가/축소
array_5 = np.array([1,2,3,4,5,6])  # 1부터 6까지의 배열 생성
print(f'ARRAY_5: {array_5.shape}')  # array_5의 형태 출력
array_5_1 = array_5[np.newaxis, :]  # array_5의 차원을 늘림 (1x6 형태로 변경)
print(array_5_1)  # array_5_1 출력
print(array_5_1.shape)  # array_5_1의 형태 출력
print('-----------------------------')  
array_1_5 = array_5[:, np.newaxis]  # array_5의 차원을 늘림 (6x1 형태로 변경)
print(array_1_5)  # array_1_5 출력
print(array_1_5.shape)  # array_1_5의 형태 출력

ages = np.array([18, 19, 25, 30, 28])  # 나이 배열 생성
print(ages[0])  # 첫 번째 나이 출력
print(ages[:])  # 모든 나이 출력
print(ages[0:2])  # 첫 번째와 두 번째 나이 출력
print(ages[1:])  # 두 번째 이후의 나이 출력

print('-----------------------------')  
scores = np.array([[99, 93, 60, ], [98, 82, 93, ], [93, 65, 81, ], [78, 82, 81, ]])  # 점수 배열 생성
print(scores.mean(axis=0))  # 각 과목의 평균 점수 출력
print(scores.mean(axis=1))  # 각 학생의 평균 점수 출력

from matplotlib import pyplot as plt  # matplotlib 라이브러리에서 pyplot 임포트
x = np.arange(0,5,1)  # 0부터 4까지의 정수 배열 생성 (독립 변수)
y1 = 2 * np.ones(5)  # y1을 2로 고정된 배열 생성
y2 = x  # y2는 x와 동일
y3 = np.square(x)  # y3는 x의 제곱 배열 생성
plt.plot(x,y1,x,y2,x,y3)  # x에 대해 y1, y2, y3를 그래프로 출력
plt.show()  # 그래프 출력

 

 


Code02

import seaborn as sns  # seaborn 라이브러리 임포트
import pandas as pd  # pandas 라이브러리 임포트

titanic = sns.load_dataset(name='titanic')  # 타이타닉 데이터셋을 로드
print(titanic)  # 데이터셋 출력
print(titanic.shape)  # 데이터셋의 형태(행, 열) 출력
titanic.to_csv(path_or_buf='titanic.csv', index=False)  # 데이터셋을 CSV 파일로 저장 (인덱스 제외)
print(titanic.isnull().sum())  # 각 열의 결측치 수 출력

print(titanic['age'])  # 나이 열의 데이터 출력 (결측치 포함)
titanic['age'] = titanic['age'].fillna(value=titanic['age'].median())  # 결측치를 나이의 중앙값으로 채움
print(titanic['age'])  # 채운 후 나이 열의 데이터 출력

print(titanic['embarked'].value_counts())  # 'embarked' 열의 고유 값 카운트 출력
print(titanic['embarked'])  # 'embarked' 열 데이터 출력 (결측치 포함)
titanic['embarked'] = titanic['embarked'].fillna(value='S')  # 결측치를 'S'로 채움
print(titanic['embarked'])  # 채운 후 'embarked' 열 데이터 출력

print(titanic['embark_town'])  # 'embark_town' 열 데이터 출력 (결측치 포함)
titanic['embark_town'] = titanic['embark_town'].fillna(value='Southampton')  # 결측치를 'Southampton'으로 채움
print(f"titanic['embark_town'] :\r\n{titanic['embark_town']}")  # 채운 후 'embark_town' 열 데이터 출력

print(titanic['deck'].value_counts())  # 'deck' 열의 고유 값 카운트 출력
print(titanic['deck'])  # 'deck' 열 데이터 출력 (결측치 포함)
titanic['deck'] = titanic['deck'].fillna(value='C')  # 결측치를 최빈값인 'C'로 채움
print(f"titanic['deck'] : \r\n{titanic['deck']}")  # 채운 후 'deck' 열 데이터 출력

print(titanic.isnull().sum())  # 결측치가 모두 채워졌는지 확인

# 타이타닉 데이터의 기본 정보 출력
titanic.info()  # 데이터프레임 정보 출력

# 타이타닉의 생존자 정보 출력
print(titanic['survived'].value_counts())  # 생존 여부 카운트 (0: 사망, 1: 생존)

import matplotlib.pyplot as plt  # matplotlib.pyplot 임포트

(f, ax) = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))  # 1행 2열의 서브플롯 생성

# 남성 생존자 비율 파이 차트
titanic['survived'][titanic['sex'] == 'male'].value_counts().plot.pie(explode=[0, 0.1], autopct='%1.1f%%', ax=ax[0], shadow=True)
ax[0].set_title('Survived(Male)')  # 남성 생존자 제목 설정

# 여성 생존자 비율 파이 차트
titanic['survived'][titanic['sex'] == 'female'].value_counts().plot.pie(explode=[0, 0.1], autopct='%1.1f%%', ax=ax[1], shadow=True)
ax[1].set_title('Survived(Female)')  # 여성 생존자 제목 설정

plt.show()  # 그래프 출력

# Pclass와 생존 여부의 관계를 나타내는 카운트 플롯
sns.countplot(x='pclass', hue='survived', data=titanic)  # Pclass에 따른 생존 여부 카운트 플롯
plt.title(label='Pclass vs Survived')  # 제목 설정
plt.show()  # 그래프 출력

# 숫자형 데이터만 선택
titanic2 = titanic.select_dtypes(include=[int, float, bool])  # 정수, 부동 소수점, 불리언 타입만 선택
print(titanic2)  # 선택된 데이터 출력
print(titanic2.shape)  # 선택된 데이터의 형태 출력

titanic_corr = titanic2.corr(method='pearson')  # 피어슨 상관 계수 계산
print(titanic_corr)  # 상관관계 출력
print(titanic_corr.shape)  # 상관관계의 형태 출력

titanic_corr.to_csv('titanic_corr.csv', index=False)  # 상관관계 데이터를 CSV 파일로 저장
print(f"성인 남자의 생존율 : {titanic['survived'].corr(titanic['adult_male'])}")  # 생존율과 성인 남자의 상관관계 출력
print(f"뱃값의 생존율 : {titanic['survived'].corr(titanic['fare'])}")  # 생존율과 뱃값의 상관관계 출력

# 산점도 (scatter)
sns.pairplot(hue='survived', data=titanic)  # 생존 여부에 따른 산점도 그리기
plt.show()  # 그래프 출력

# 히트맵을 통해 상관관계 시각화
# 나이 문제를 해결하기 위한 데이터 전처리
import pandas as pd  # pandas 라이브러리 임포트
import seaborn as sns  # seaborn 라이브러리 임포트
import matplotlib.pyplot as plt  # matplotlib.pyplot 임포트

# 10, 20, 30, 40, 50, 60, 70의 나이 범주화 함수 정의
def category_age(x: int) -> int:
    if x < 10: return 0  # 10세 미만
    elif x < 20: return 1  # 10세 이상 20세 미만
    elif x < 30: return 2  # 20세 이상 30세 미만
    elif x < 40: return 3  # 30세 이상 40세 미만
    elif x < 50: return 4  # 40세 이상 50세 미만
    elif x < 60: return 5  # 50세 이상 60세 미만
    elif x < 70: return 6  # 60세 이상 70세 미만
    else: return 7  # 70세 이상

titanic['age2'] = titanic['age'].apply(category_age)  # 나이를 범주화하여 'age2' 열에 저장
titanic['sex'] = titanic['sex'].map({'male': 1, 'female': 0})  # 성별을 1(남성)과 0(여성)으로 변환
titanic['family'] = titanic['sibsp'] + titanic['parch'] + 1  # 가족 크기 계산 (형제/자매 + 부모/자식 + 본인)
titanic.to_csv('NewTitanic.csv', index=False)  # 수정된 데이터셋을 CSV 파일로 저장

# 생존 여부, 성별, 나이 범주, 가족 수, 선실 등급, 뱃값을 포함한 데이터 선택
heat_map = titanic[['survived', 'sex', 'age2', 'family', 'pclass', 'fare']]
color_map = plt.cm.RdBu  # 색상 맵 설정
sns.heatmap(heat_map.astype(float).corr(), linewidths=0.2, vmax=1.0, square=True,
            cmap=color_map, linecolor='white', annot=True, annot_kws={'size': 8})  # 히트맵 생성
plt.show()  # 그래프 출력

위 코드는 타이타닉 데이터셋을 분석하고 시각화하는 일련의 과정을 포함합니다.

  1. 데이터 로드 및 확인: Seaborn을 이용해 타이타닉 데이터셋을 로드하고, 데이터의 형태와 결측치를 확인합니다.
  2. 결측치 처리: 나이, 탑승 항구, 탑승한 배의 갑판 등 결측치를 적절한 값(중앙값, 최빈값 등)으로 대체합니다.
  3. 기본 정보 출력: 데이터프레임의 정보와 생존 여부(0: 사망, 1: 생존)에 대한 통계를 출력합니다.
  4. 시각화:
    • 성별에 따른 생존자 비율을 파이 차트로 시각화합니다.
    • Pclass(선실 등급)와 생존 여부의 관계를 카운트 플롯으로 시각화합니다.
  5. 상관관계 분석: 숫자형 데이터만 선택하고, 피어슨 상관계수를 계산하여 CSV 파일로 저장합니다.
  6. 데이터 전처리: 나이를 범주화하고, 성별을 숫자로 변환하며, 가족 수를 계산합니다.
  7. 히트맵 시각화: 생존 여부, 성별, 나이 범주, 가족 수, 선실 등급, 뱃값 간의 상관관계를 히트맵으로 시각화합니다.