목록Python (17)
Jun's Blog

KNN(K-Nearest Neighbors, K 최근접 이웃)은 머신러닝에서 사용되는 분류(classification) 또는 회귀(regression) 알고리즘 중 하나입니다. KNN은 주변의 가까운 데이터를 기반으로 예측을 수행하는 알고리즘입니다. # 기본 라이브러리 불러오기import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt# 그래프의 폰트를 'Malgun Gothic'으로 설정하여 한글 폰트가 잘 보이도록 함plt.rc('font', family='Malgun Gothic')# 그래프에서 음수 기호를 제대로 표시하도록 설정plt.rcParams['axes.unicode_minus'] = False# [Step 1] 데이터 ..

import numpy as npdataIn, dataOut = './../dataIn/', './../dataOut/'filename = dataIn + 'iris.csv'data = np.loadtxt(filename, skiprows=1, delimiter=',', dtype='str')print(f'data.nim={data.ndim}')# 최대 10글자의 유니코드 문자열 배열print(f'data.dtype={data.dtype}')print(f'data.shape={data.shape}') column_size = data.shape[1]y_column = 1x_column = column_size - y_columnx = data[:, 0:x_column]x = x.astype(float) ..

클래스 분류(Classification)는 주어진 입력 데이터를 여러 카테고리(클래스) 중 하나로 분류하는 것을 의미합니다.SVM(Support Vector Machine)은 이러한 클래스 분류 문제를 해결하는 데 사용되는 강력한 알고리즘 중 하나입니다. SVM은 데이터를 최적으로 분리하는 경계를 찾는 방법입니다. 1. seaborn 라이브러리에 제공되는 타이타닉(titanic)을 활용하여 SVM 실습 해보기import seaborn as snsdf = sns.load_dataset('titanic')print(type(df))print(df.columns)print(df['survived'].value_counts())print('중복되는 행의 개수 : ' + str(sum(df.duplicate..

회귀분석 및 활용 예시의 데이터들을 이어서 활용하여 다중 회귀 분석을 진행하였습니다. print('multidf.columns')print(multidf.columns)# 독립 변수와 종속 변수를 분리independent_variable = ['cylinders', 'horsepower', 'weight']x = multidf[independent_variable]y = multidf['mpg']# 훈련용 데이터와 테스트용 데이터 분리x_train, x_test, y_train, y_test = \ train_test_split(x, y, test_size=0.3, random_state=10)print(f'훈련용 데이터 형상 : {x_train.shape}')print(f'테스트용 데이터 형상 :..

1. 데이터셋import numpy as npnp.random.seed(42)x = np.random.randn(20, 3) # 20행 3열의 랜덤 데이터 셋print(x) y = np.concatenate([np.zeros(10), np.ones(10)])print(y) data = np.column_stack((x, y))print(data) # x : 입력 데이터(시험 문제지 - 특성(feature))x = data[:, :-1] # 마지막 열을 제외한 추출# y : 출력 데이터(답지 - Label)y = data[:, -1] # 마지막 열만 추출# x_train : 내가 열심히 공부하는 기출 문제지# y_train : 공부하면서 같이 보는 답지# x_test : 열심히 공부했는지 점검하기 위한 ..

1. 결측치 결측치(Missing Value)란 데이터 분석에서 값이 누락된 데이터를 의미합니다.즉, 특정 변수나 열에 대해 값이 존재하지 않거나 측정되지 않은 경우를 말합니다. 결측치는 데이터의 품질에 영향을 미칠 수 있으며, 분석 및 모델링 과정에서 적절한 처리가 필요합니다. import pandas as pdimport numpy as npdata ={ 'a': [1, 2, np.nan, np.nan, 5], # 결측치 2개 'b': [np.nan, 2, np.nan, 4, np.nan] # 결측치 3개}df = pd.DataFrame(data)print(df)print(df.info()) missing_value_count = df.isna().sum()print(missing_v..
넘파이 https://numpy.org/doc/stable/genindex.html Index — NumPy v2.2 Manual numpy.org 판다스 https://pandas.pydata.org/docs/reference/index.html API reference — pandas 2.2.3 documentationThis page gives an overview of all public pandas objects, functions and methods. All classes and functions exposed in pandas.* namespace are public. The following subpackages are public. In addition, public functions ..

1. 혼합 데이터에서 원하는 항목들만 추출해보기주어진 list에서 문자열 2개와 숫자 3개로 구성된 항목들 찾기import refrom jupyter_core.version import patternprint('문자열 2개와 숫자 3개로 구성된 항목들 찾기')mylist = ['ab123','cd456','ef789','abc12']# regex = '[a-z]{2}[0-9]{3}' # 정규 표현식regex = '[a-z]{2}\d{3}' # \d 는 숫자 1개를 의미하고 [0-9]와 동일한 의미pattern = re.compile(regex) # 정규식 패턴for item in mylist: if pattern.match(item): print(f'문자열 {item}은 조건에 적합합니..

1. JSON 파일로부터 데이터 읽어오기1.1 JSON 파일 생성하기[ { "name": "이연수", "kor": "60.0", "eng": "70.0", "math": "80.0", "hello": "여러분 안녕~~", "gender": "F" }, { "name": "강민섭", "kor": "65.0", "eng": "75.0", "math": "85.0", "gender": "M" }] 1.2 JSON 파일의 내용을 읽어오기filename = 'JsonTest.json'myfile = open(file=filename, mode='rt', ..

1. XML 파일로부터 데이터 읽어오기1.1 XML 파일 생성하기 현대 소나타 2022 White 기아 K7 2023 Black 1.2 xml 파일 참조하는 Python 파일 구현하기# import math# from math import sqrtfrom xml.etree.ElementTree import parse# print(math.sqrt(4))tree = parse(source='Car_Info.xml')myroot = tree.getroot()print(type(myroot))carList = myroot.findall('car')print('총 car 수 :..