tlswjdgns016의 등록된 링크

키자드에 등록된 총 173개의 포스트를 확인하실 수 있습니다.

Naver Blog

20221206 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 ai(딥러닝) 과제 보고서.py 파일 다운로드 # 기본문법 my_list = [10, 'hello list', 20] print(my_list[1]) my_list_2 = [[10, 20, 30], [40, 50, 60]] print(my_list_2[1][1]) import numpy as np my_arr = np.array([[10, 20, 30], [40, 50, 60]]) print(my_arr) type(my_arr) my_arr[0][2] np.sum(my_arr) print(my_arr[1][0]) import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25]) # x 좌표와 y 좌표를 파이썬 리스트로 전달합니다. plt.show() plt.scatter([1, 2, 3, 4, 5], [1, 4, 9, 16, 25]) plt.show() x = np.random.randn(1000) #

Naver Blog

20221207 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 딥러닝입문.1207.py 파일 다운로드 # 훈련 노하우 import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split cancer = load_breast_cancer() x = cancer.data y = cancer.target x_train_all, x_test, y_train_all, y_test = train_test_split(x, y, stratify=y, test_size=0.2, random_state=42) from sklearn.linear_model import SGDClassifier sgd = SGDClassifier(loss='log', random_state=42) sgd.fit(x_train_all, y_train_all) sgd.scor

Naver Blog

20221208 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 딥러닝입문.1208.py 파일 다운로드 # 다중분류 신경망 import numpy as np class MultiClassNetwork: def __init__(self, units=10, batch_size=32, learning_rate=0.1, l1=0, l2=0): self.units = units # 은닉층의 뉴런 개수 self.batch_size = batch_size # 배치 크기 self.w1 = None # 은닉층의 가중치 self.b1 = None # 은닉층의 절편 self.w2 = None # 출력층의 가중치 self.b2 = None # 출력층의 절편 self.a1 = None # 은닉층의 활성화 출력 self.losses = [] # 훈련 손실 self.val_losses = [] # 검증 손실 self.lr = learning_rate # 학습률 self.l1 = l1 # L1 손실 하이퍼파라미터 self.l2 = l2 # L2 손실 하이퍼파라미터

Naver Blog

20221209 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 딥러닝입문.1209.py 파일 다운로드 # 합성곱 import numpy as np w = np.array([2, 1, 5, 3]) x = np.array([2, 8, 3, 7, 1, 2, 0, 4, 5]) w_r = np.flip(w) print(w_r) w[0:4:2] for i in range(6): print(np.dot(x[i:i+4], w_r)) from scipy.signal import convolve convolve(x, w, mode='valid') from scipy.signal import correlate correlate(x, w, mode='valid') correlate(x, w, mode='full') correlate(x, w, mode='same') x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) w = np.array([[2, 0], [0, 0]]) from scipy.signal import corr

Naver Blog

20221219 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 딥러닝입문.1219.py 파일 다운로드 # 텍스트 분류 # 순환 신경망 생성 import numpy as np from tensorflow.keras.datasets import imdb (x_train_all, y_train_all), (x_test, y_test) = imdb.load_data(skip_top=20, num_words=100) print(x_train_all[0]) for i in range(len(x_train_all)): x_train_all[i] = [w for w in x_train_all[i] if w > 2] print(x_train_all[0]) word_to_index = imdb.get_word_index() word_to_index['movie'] index_to_word = {word_to_index[k]: k for k in word_to_index} for w in x_train_all[0]: print(index_to_word[w

Naver Blog

20221220 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 py221219.py 파일 다운로드 a = 5 b = 7 c = a + b print(c) import numpy as np x=np.array([1,2,3]) x.__class__ x.shape x.ndim w = np.array([[1,2,3],[4,5,6]]) w.shape w.ndim w = np.array([[1,2,3],[4,5,6]]) x = np.array([[0,1,2],[3,4,5]]) w+x w*x A= np.array([[1,2],[3,4]]) A*10 A= np.array([[1,2],[3,4]]) b= np.array([10,20]) A*b a = np.array([1,2,3]) b = np.array([4,5,6]) np.dot(a,b) A= np.array([[1,2],[3,4]]) B= np.array([[5,6],[7,8]]) np.matmul(A,B) import numpy as np w1 = np.random.randn(2,4) b1 =

Naver Blog

[py] T1-16. 분산 Expected Question

문제 # 주어진 데이터 셋에서 f2가 0값인 데이터를 age를 기준으로 오름차순 정렬하고 # 앞에서 부터 20개의 데이터를 추출한 후 # f1 결측치(최소값)를 채우기 전과 후의 분산 차이를 계산하시오 (소수점 둘째 자리까지) # - 데이터셋 : basic1.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") dfage = df[df["f2"]==0].sort_values("age").head(20) dfmin = dfage.fillna(dfage["f1"].min()) round(dfage["f1"].var()-dfmin["f1"].var(),2) 코드사용 sort_values : 정렬 fillna : 결측치 대체 var : 분산

Naver Blog

[py] T1-17. 시계열 데이터1 Expected Question

문제 2022년 5월 sales의 중앙값을 구하시오 데이터셋 : basic2.csv 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic2.csv") df["Date"]=pd.to_datetime(df["Date"],format='%Y-%m-%d') df["Sales"][df["Date"].between('2022-05-01','2022-05-31')].median() 사용코드 to_datetime : 데이터 형태를 변화 between : 사이값을 찾기위해

Naver Blog

[py] T1-18. 시계열 데이터2 Expected Question

문제 주어진 데이터에서 2022년 5월 주말과 평일의 sales컬럼 평균값 차이를 구하시오 (소수점 둘째자리까지 출력, 반올림) 데이터셋 : basic2.csv 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic2.csv", parse_dates=['Date']) df["Date"]=pd.to_datetime(df["Date"]) df5 = df[(df["Date"].dt.month == 5)& (df["Date"].dt.year == 2022)] df1 = df5[df["Date"].dt.dayofweek.isin([5,6])]["Sales"].mean() df2 = df5[df["Date"].dt.dayofweek.isin([0,1,2,3,4,])]["Sales"].mean() round((df1-df2),2) 코드사용 to_datetime : 날짜로 형태 변환 dt.month : 월별 추출

Naver Blog

[py] T1-19. 시계열 데이터3 Expected Question

정답 주어진 데이터에서 2022년 월별 Sales 합계 중 가장 큰 금액과 2023년 월별 Sales 합계 중 가장 큰 금액의 차이를 절대값으로 구하시오. 단 Events컬럼이 '1'인경우 80%의 Salse값만 반영함 (최종값은 소수점 반올림 후 정수 출력) 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic2.csv", parse_dates=['Date']) df["Date"] = pd.to_datetime(df["Date"]) df22 = df[df["Date"].dt.year == 2022] def appl(x): if x["Events"] == 1 : x["Sales"]= x["Sales"]*0.8 elif x["Events"] != 1 : x["Sales"]=x["Sales"] return x df22 = df22.apply(lambda x : appl(x), axis=1) df22

Naver Blog

[py] T1-20. 데이터 병합 Expected Question

문제 고객과 잘 맞는 타입 추천 :) basic1 데이터와 basic3 데이터를 'f4'값을 기준으로 병합하고, 병합한 데이터에서 r2결측치를 제거한다음, 앞에서 부터 20개 데이터를 선택하고 'f2'컬럼 합을 구하시오 basic1.csv: 고객 데이터 basic3.csv: 잘 어울리는 관계 데이터 (추천1:r1, 추천2:r2) 풀이 import pandas as pd b1 = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") b3 = pd.read_csv("../input/bigdatacertificationkr/basic3.csv") b2 = pd.merge(b1,b3, how='left',on="f4") b2[~b2["r2"].isnull()].head(20)["f2"].sum() 코드사용 merge : 데이터 합치기 isnull : 결측치 확인

Naver Blog

화면구현[R, python]

첨부파일 B4_통계 기법을 활용한 데이터 분석 및 시각화 보고서.pdf 파일 다운로드 첨부파일 B4_rcode.R 파일 다운로드 첨부파일 B4_pythoncode.py 파일 다운로드

Naver Blog

[py] T1-21. 구간 분할 Expected Question

문제 나이 구간 나누기 basic1 데이터 중 'age'컬럼 이상치를 제거하고, 동일한 개수로 나이 순으로 3그룹으로 나눈 뒤 각 그룹의 중앙값을 더하시오 (이상치는 음수(0포함), 소수점 값) data: basic1.csv 풀이 import pandas as pd df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df["age"].describe() dfage = df[(df["age"]>0) &(df["age"]==round(df["age"],0))] dfage = dfage.sort_values(by = "age",ascending=False) dfage["age1"] = pd.qcut(dfage["age"],3,labels=[1,2,3]) dfage.groupby("age1")["age"].median().sum() 코드사용 sort_values : 순차적으로 변경 qcut : 분할

Naver Blog

T1-22. Time-Series4 (Weekly data)

문제 주어진 데이터(basic2.csv)에서 주 단위 Sales의 합계를 구하고, 가장 큰 값을 가진 주와 작은 값을 가진 주의 차이를 구하시오(절대값) 데이터셋 : basic2.csv 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic2.csv", parse_dates=['Date'], index_col=0) df.head() df["sale2"]=df["Sales"].resample("W").sum() df["sale2"].max()-df["sale2"].min() 코드사용 resample : 주간별 샘플링

Naver Blog

T1-23. 중복 데이터 제거 Drop Duplicates

문제 f1의 결측치를 채운 후 age 컬럼의 중복 제거 전과 후의 'f1' 중앙값 차이를 구하시오 - 결측치는 f1의 데이터 중 내림차순 정렬 후 10번째 값으로 채움 - 중복 데이터 발생시 뒤에 나오는 데이터를 삭제함 - 최종 결과값은 절대값으로 출력 데이터셋 : basic1.csv 풀이 import pandas as pd df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df = df.sort_values(by="f1") df["f1"] = df["f1"].fillna(df["f1"].iloc[9]) df1 = df.drop_duplicates(["age"]) abs(df["f1"].median()-df1["f1"].median()) 코드사용 sort_values : 내림차순 fillna : 결측치 대처 drop_duplicates : 중복제거

Naver Blog

T1-24. Time-Series5 (Lagged Feature) 시차 데이터 생성

문제 주어진 데이터(basic2.csv)에서 "pv"컬럼으로 1일 시차(lag)가 있는 새로운 컬럼을 만들고(예: 1월 2일에는 1월 1일 pv데이터를 넣고, 1월 3일에는 1월 2일 pv데이터를 넣음),새로운 컬럼의 1월 1일은 다음날(1월 2일)데이터로 결측치를 채운 다음, Events가 1이면서 Sales가 1000000이하인 조건에 맞는 새로운 컬럼 합을 구하시오 데이터셋 : basic2.csv 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic2.csv") df["Date"] = pd.to_datetime(df["Date"]) df["PV1"] = df["PV"].shift(1) df = df.fillna(method = "bfill") df[(df["Events"]==1)&(df["Sales"]<1000000)]["PV1"].sum() 코드사용 to_datetime : 형태 변환 sh

Naver Blog

[py] T1-6. 결측치 제거 및 그룹 합계 Expected Questions

문제 결측치 제거 및 그룹 합계에서 조건에 맞는 값 찾아 출력 주어진 데이터 중 basic1.csv에서 'f1'컬럼 결측 데이터를 제거하고, 'city'와 'f2'을 기준으로 묶어 합계를 구하고, 'city가 경기이면서 f2가 0'인 조건에 만족하는 f1 값을 구하시오 데이터셋 : basic1.csv 풀이 # 라이브러리 및 데이터 불러오기 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df.head() df_dropna = df.dropna(subset = ["f1"]) df_fn = df_dropna.groupby(["city","f2"]).sum() df_fn = df_fn.loc["경기",0]["f1"] df_fn 코드 dropna : 결측치 제거 grouby : city, f2 기준으로 계산하기위해서

Naver Blog

[py] T1-7. 값 변경 및 2개 이상의 조건 Expected Questions

문제 'f4'컬럼의 값이 'ESFJ'인 데이터를 'ISFJ'로 대체하고, 'city'가 '경기'이면서 'f4'가 'ISFJ'인 데이터 중 'age'컬럼의 최대값을 출력하시오! 데이터셋 : basic1.csv 풀이 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df.head() df.loc[df["f4"]=="ESFJ"] = 'ISFJ' df.loc[(df["f4"]== "ISFJ")&(df["city"]=="경기")]["age"].max() 사용코드 max : 최고값을 찾기위해 사용

Naver Blog

[py] T1-8. 누적합 그리고 보간(결측치 처리) Expected Questions

문제 주어진 데이터 셋에서 'f2' 컬럼이 1인 조건에 해당하는 데이터의 'f1'컬럼 누적합을 계산한다. 이때 발생하는 누적합 결측치는 바로 뒤의 값을 채우고, 누적합의 평균값을 출력한다. (단, 결측치 바로 뒤의 값이 없으면 다음에 나오는 값을 채워넣는다) 데이터셋 : basic1.csv 풀이 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df.head(2) df_cumsum = df[df["f2"]==1]["f1"].cumsum() df_cumsum.fillna(method="bfill").mean() 사용코드 cumsum : 누적합 fillna(method="bfill") : 결측치 변경 mean : 평균

Naver Blog

[py] T1-9. 수치형 변수 표준화 Expected Questions

문제 수치형 변수 변환하기 주어진 데이터에서 'f5'컬럼을 표준화(Standardization (Z-score Normalization))하고 그 중앙값을 구하시오 데이터셋 : basic1.csv 풀이 # 라이브러리 및 데이터 불러오기 import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') scaler = StandardScaler() scaler.fit(df[["f5"]]) df["f5"]=scaler.fit_transform(df[["f5"]]) df["f5"].median() 사용코드 StandardScaler : 표준화 fi_tranform : 데이터정규화

Naver Blog

[py] T1-10. 여-존슨과 박스-칵스 변환 Expected Questions

문제 수치형 변수 변환하기 주어진 데이터에서 20세 이상인 데이터를 추출하고 'f1'컬럼을 결측치를 최빈값으로 채운 후, f1 컬럼의 여-존슨과 박스콕스 변환 값을 구하고, 두 값의 차이를 절대값으로 구한다음 모두 더해 소수점 둘째 자리까지 출력(반올림)하시오 데이터셋 : basic1.csv 해결 import pandas as pd import numpy as np from sklearn.preprocessing import power_transform df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df20 = df[df["age"]>=20] many = df20["f1"].mode() df20["f1"] = df20["f1"].fillna(many[0]) df20["a"] = power_transform(df20[["f1"]],standardize=False) df20["b"] = power_transform(df2

Naver Blog

[py] T1-11. min-max & 상하위 5%값 Expected Questions

문제 # min-max스케일링 기준 상하위 5% 구하기 # 주어진 데이터에서 'f5'컬럼을 min-max 스케일 변환한 후, # 상위 5%와 하위 5% 값의 합을 구하시오 # - 데이터셋 : basic1.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script 해결 import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') min_max_scaler = MinMaxScaler() df["scaler"] = min_max_scaler.fit_transform(df[["f5"]]) print(df.head()) scaler = df["scaler"] (scaler.quantile(0.05)+scaler.q

Naver Blog

[py] T1-12. 상위 10개, 하위 10개 차이 Expected Questions

문제 # 주어진 데이터에서 상위 10개 국가의 접종률 평균과 하위 10개 국가의 접종률 평균을 구하고, 그 차이를 구해보세요 # (단, 100%가 넘는 접종률 제거, 소수 첫째자리까지 출력) # - 데이터셋 : ../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script 풀이 import pandas as pd df = pd.read_csv("../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv") dfmax = df.groupby("country")["ratio"].max() print(dfmax.tail()) dfmax = dfmax.sort_values(ascending = False) dfmax = dfm

Naver Blog

[py] T1-13. 상관관계 구하기 Expected Questions

문제 # 상관관계 구하기 # 주어진 데이터에서 상관관계를 구하고, quality와의 상관관계가 가장 큰 값과, 가장 작은 값을 구한 다음 더하시오! # 단, quality와 quality 상관관계 제외, 소수점 둘째 자리까지 출력 # - 데이터셋 : ../input/red-wine-quality-cortez-et-al-2009/winequality-red.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - 스크립트 방식 권장: File -> Editor Type -> Script 해설 import pandas as pd import numpy as np df = pd.read_csv("../input/red-wine-quality-cortez-et-al-2009/winequality-red.csv") print(df.head()) dfcor = df.corr() dfmax = abs(dfcor[dfcor["quality"]!=1]["quality"]).

Naver Blog

[py] T1-14. 2개 조건에 따른 상위 값 Expected Question

문제 # city와 f4를 기준으로 f5의 평균값을 구한 다음, f5를 기준으로 상위 7개 값을 모두 더해 출력하시오 (소수점 둘째자리까지 출력) # - 데이터셋 : basic1.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script 풀이 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") df.head() dfgr=df.groupby(["city","f4"])["f5"].mean() round(dfgr.reset_index().sort_values("f5",ascending = False).head(7)["f5"].sum(),2) 코드사용 groupby : city, f4 기준으로 f5를 평균 reset_index : f5로 다시 정렬 sort_values : 순차적으로 변경

Naver Blog

[py] T1-15. 슬라이싱 & 조건 Expected Question

문제 # %% [code] # 주어진 데이터 셋에서 age컬럼 상위 20개의 데이터를 구한 다음 # f1의 결측치를 중앙값으로 채운다. # 그리고 f4가 ISFJ와 f5가 20 이상인 # f1의 평균값을 출력하시오! # - 데이터셋 : basic1.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script 해결 import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") dfage = df.sort_values("age",ascending=False).head(20) dfage = dfage.fillna(dfage["f1"].median()) dfage["f1"][(dfage["f4"] =="ISFJ")&(dfage["f5"]>=20)].mean() 코드사용 sort_values : 순서 정령 fillna : 결측치 대처

Naver Blog

20221122 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1122_training.R 파일 다운로드 # 토픽모델링 # 06-2 -------------------------------------------------------------------- # 기생충 기사 댓글 불러오기 library(readr) library(dplyr) raw_news_comment <- read_csv("news_comment_parasite.csv") %>% mutate(id = row_number()) # ------------------------------------------------------------------------- library(stringr) library(textclean) # 기본적인 전처리 news_comment <- raw_news_comment %>% mutate(reply = str_replace_all(reply, "[^가-힣]", " "), reply = str_squish(reply)) %>% # 중복 댓글

Naver Blog

R 데이터 시각화

첨부파일 R_ch5_데이터시각화_221123.pdf 파일 다운로드

Naver Blog

R 고급시각화

첨부파일 R_ch8_고급시각화_221124.pdf 파일 다운로드 첨부파일 R ch8 연습문제_221123.pdf 파일 다운로드

Naver Blog

20221123 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1123_training.R 파일 다운로드 # 데이터 시각화 # 1단계: 차트 작성을 위한 자료 만들기 chart_data <- c(305, 450, 320, 460, 330, 480, 380, 520) names(chart_data) <- c("2018 1분기", "2019 1분기", "2018 2분기", "2019 2분기", "2018 3분기", "2019 3분기", "2018 4분기", "2019 4분기") str(chart_data) chart_data # 2단계: 세로 막대 차트 그리기 barplot(chart_data, ylim = c(0, 600), col = rainbow(8), main = "2018년도 vs 2019년도 매출현항 비교") barplot(chart_data, ylim = c(0, 600), ylab = "매출액(단위: 만원)", xlab = "년도별 분기 현황", col = rainbow(8), main= "2018년도 vs 2019년도 매출

Naver Blog

20221124 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1124_training.R 파일 다운로드 # # 실습 (lattice 패키지 사용 준비하기) # 1단계: lattice 패키지 설치 # install.packages("lattice") library(lattice) # 2단계: 실습용 테이터 가져오기 # install.packages("mlmRev") library(mlmRev) data("Chem97") str(Chem97) head(Chem97, 30) Chem97 # 실습 (score 변수를 조건변수로 지정하여 데이터 시각화하기) histogram(~gcsescore | score, data = Chem97) histogram(~gcsescore | factor(score), data = Chem97) # 실습 (densityplot()함수를 사용하여 밀도 그래프 그리기) densityplot(~gcsescore | factor(score), data = Chem97, groups = gender, plot.Poin

Naver Blog

20221125 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 데이터 분석 및 시각화.py 파일 다운로드

Naver Blog

[py] T1-1. 이상치를 찾아라(IQR활용) Expected Questions

문제 ## 이상치를 찾아라 ### 데이터에서 IQR을 활용해 Fare컬럼의 이상치를 찾고, 이상치 데이터의 여성 수를 구하시오 - 강의 영상 : https://youtu.be/ipBW5D_UJEo - 데이터셋 : titanic - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 - 데이터 위치 "../input/titanic/train.csv" (copy&edit가 아닐 경우 별도로 데이터셋 불러와야 함) 풀이 import pandas as pd import numpy as np df = pd.read_csv('../input/titanic/train.csv') df["Fare"].describe() q1=df["Fare"].quantile(0.25) q3=df["Fare"].quantile(0.75) iqr=q3-q1 df_iqr = df["Fare"]<q1-1.5*iqr df_iqr1 = df["Fare"]>q3+1.5*iqr df_df = df[df_iqr|df_i

Naver Blog

[py] T1-2. 이상치를 찾아라(소수점 나이) Expected Questions

문제 이상치를 찾아라(소수점 나이) 주어진 데이터에서 이상치(소수점 나이)를 찾고 올림, 내림, 버림(절사)했을때 3가지 모두 이상치 'age' 평균을 구한 다음 모두 더하여 출력하시오 풀이 # 라이브러리 및 데이터 불러오기 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df.head() df = df[(df["age"]-np.floor(df["age"]))!=0] df df_mean = np.floor(df["age"]).mean()+np.ceil(df["age"]).mean()+np.round(df["age"].mean()) df_mean 사용함수 floor = 소수점 내림 ceil = 소수점 올림 round = 소수점 반올림

Naver Blog

[py] T1-3. 결측치 처리(map 활용) Expected Questions

문제 ## 결측치 처리 - 주어진 데이터에서 결측치가 80%이상 되는 컬럼은(변수는) 삭제하고, 80% 미만인 결측치가 있는 컬럼은 'city'별 중앙값으로 값을 대체하고 'f1'컬럼의 평균값을 출력하세요! - 데이터셋 : basic1.csv 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 해결 # 라이브러리 및 데이터 불러오기 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') df.head() df_bool = df.isnull().sum()/len(df.index) < 0.8 df_loc = df.loc[:,df_bool] df_city = df_loc.groupby("city")['f1'].median() df_fillna = df_loc.fillna(df_city) df['f1'] = df['f1'].fillna(df['city'].

Naver Blog

[py] T1-4. 왜도와 첨도 구하기 (로그스케일) Expected Questions

문제 # 왜도와 첨도 구하기 # 주어진 데이터 중 train.csv에서 'SalePrice'컬럼의 왜도와 첨도를 구한 값과, # 'SalePrice'컬럼을 스케일링(log1p)로 변환한 이후 왜도와 첨도를 구해 # 모두 더한 다음 소수점 2째자리까지 출력하시오 # 데이터셋 : House Prices - Advanced Regression Technique (https://www.kaggle.com/c/house-prices-advanced-regression-techniques) # 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # 강의 영상 : https://youtu.be/_ft7ZlDlk7c 풀이 import pandas as pd import numpy as np df = pd.read_csv("../input/house-prices-advanced-regression-techniques/train.csv") df_skew = df['SalePrice'].ske

Naver Blog

[py] T1-5. 조건에 맞는 데이터 표준편차 구하기 Expected Questions

문제 조건에 맞는 데이터 표준편차 구하기¶ 주어진 데이터 중 basic1.csv에서 'f4'컬럼 값이 'ENFJ'와 'INFP'인 'f1'의 표준편차 차이를 절대값으로 구하시오 데이터셋 : basic1.csv 해결 import pandas as pd import numpy as np df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv') ENFJ = df[df["f4"]=="ENFJ"]["f1"].std() INFP = df[df["f4"]=="INFP"]["f1"].std() abs(ENFJ-INFP) 사용코드 std : 표준편차 abs : 절대값

Naver Blog

20221116 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1116_training.R 파일 다운로드 # 텍스트마이닝 # install.packages("multilinguer") library(multilinguer) # install_jdk() # install.packages("remotes") # remotes::install_github("haven-jeon/KoNLP", upgrade = "never", INSTALL_opts = c("--no-multiarch")) # install.packages(c("stringr", "hash", "tau", "Sejong", "RSQLite", "devtools"),type = "binary") # install.packages("rJava") # install.packages ("wordcloud") # install.packages ("tm") library(KoNLP) useNIADic() # install.packages("Sejong") # install.packages

Naver Blog

R 감정분석

첨부파일 04 감정 분석_e.pdf 파일 다운로드 첨부파일 R_TM_4.감정분석.pdf 파일 다운로드 첨부파일 08.텍스트+마이닝+기반+데이터+분석(LM2001010508_15v1) (1).pdf 파일 다운로드

Naver Blog

R 빈도분석

첨부파일 01 단어 빈도 분석_e.pdf 파일 다운로드 첨부파일 R_TM_1.빈도분석.pdf 파일 다운로드

Naver Blog

20221117 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1117_training.R 파일 다운로드 # 감정분석 # 04-1 -------------------------------------------------------------------- # 감정 사전 불러오기 install.packages("readr") library(readr) dic <- read_csv("knu_sentiment_lexicon.csv") # ------------------------------------------------------------------------- library(dplyr) # 긍정 단어 dic %>% filter(polarity == 2) %>% arrange(word) # 부정 단어 dic %>% filter(polarity == -2) %>% arrange(word) # ------------------------------------------------------------------------- dic %>% f

Naver Blog

R 형태소 빈도분석

첨부파일 02 형태소 분석기 이용 단어 빈도 분석_e.pdf 파일 다운로드 첨부파일 R_TM_2.형태소분석기이용빈도분석.pdf 파일 다운로드

Naver Blog

20221118 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1118_training.R 파일 다운로드 # 형태소분석기 이용 빈도분석 # 02-1 -------------------------------------------------------------------- # install.packages("multilinguer") library(multilinguer) # install_jdk() # install.packages(c("stringr", "hash", "tau", "Sejong", "RSQLite", "devtools"), # type = "binary") # install.packages("remotes") # remotes::install_github("haven-jeon/KoNLP", # upgrade = "never", # INSTALL_opts = c("--no-multiarch")) library(KoNLP) useNIADic() # -----------------------------------------

Naver Blog

R 비교분석_오즈비_TF-IDF

첨부파일 03 비교 분석_오즈비_TF-IDF.pdf 파일 다운로드 첨부파일 R_TM_3.비교분석_오즈비_TF-IDF.pdf 파일 다운로드

Naver Blog

R 의미망 분석

첨부파일 05 의미망 분석_e.pdf 파일 다운로드 첨부파일 R_TM_5.의미망분석.pdf 파일 다운로드

Naver Blog

20221121 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1121_training.R 파일 다운로드 library(dplyr) # 문재인 대통령 연설문 불러오기 raw_moon <- readLines("speech_moon.txt", encoding = "UTF-8") moon <- raw_moon %>% as_tibble() %>% mutate(president = "moon") # 박근혜 대통령 연설문 불러오기 raw_park <- readLines("speech_park.txt", encoding = "UTF-8") park <- raw_park %>% as_tibble() %>% mutate(president = "park") bind_speeches <- bind_rows(moon, park) %>% select(president, value) # 기본적인 전처리 library(stringr) speeches <- bind_speeches %>% mutate(value = str_replace_all(value, "[^가

Naver Blog

R 토픽 모델링

첨부파일 06 토픽 모델링_e.pdf 파일 다운로드 첨부파일 R_TM_6.토픽모델링.pdf 파일 다운로드

Naver Blog

20221115 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1115_training.R 파일 다운로드 # xgboos # 1단계: 패키지 설치 install.packages("xgboost") library(xgboost) # 2단계: y변수 생성 iris_label <- ifelse(iris$Species == 'setosa', 0, ifelse(iris$Species == 'versicolor', 1, 2)) table(iris_label) iris$label <- iris_label # 3단계: data set 생성 idx <- sample(nrow(iris), 0.7 * nrow(iris)) train <- iris[idx, ] test <- iris[-idx, ] # 4단계: matrix 객체 변환 train_mat <- as.matrix(train[-c(5:6)]) dim(train_mat) train_lab <- train$label length(train_lab) # 5단계: xgb.DMatrix 객체 변환 dtrai

Naver Blog

R 텍스트마이닝

첨부파일 R_ch9_TM(텍스트마이닝)_221116.pdf 파일 다운로드

Naver Blog

RNN_임베딩

import torch import torch.nn as nn import torch.optim as optim sentence = "Repeat is the best medicine for memory".split() vocab = list(set(sentence)) print(vocab) word2index = {tkn: i for i, tkn in enumerate(vocab, 1)} # 단어에 고유한 정수 부여 word2index['<unk>']=0 print(word2index) print(word2index['memory']) # 수치화된 데이터를 단어로 바꾸기 위한 사전 index2word = {v: k for k, v in word2index.items()} print(index2word) print(index2word[2]) def build_data(sentence, word2index): encoded = [word2index[token] for token in

Naver Blog

20221114 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1114_training.R 파일 다운로드 # 연관분석 # 1단계: 연관분석을 위한 패키지 설치 install.packages("arules") library(arules) # 2단계: 트랜잭션(transaction) 객체 생성 setwd("C:/Rwork/ ") tran <- read.transactions("tran.txt", format = "basket", sep = ",") tran # 3단계: 트랜잭션 데이터 보기 inspect(tran) # 4단계: 규칙(rule) 발견1 rule <- apriori(tran, parameter = list(supp = 0.3, conf = 0.1)) inspect(rule) # 5단계: 규칙(rule) 발견2 rule <- apriori(tran, parameter = list(supp = 0.1, conf = 0.1)) inspect(rule) # 2.2 트랜잭션 객체 생성 # 실습 (single 트랜잭션 객체 생성) set

Naver Blog

Oracle R,python DB접근

첨부파일 R과 python을 이용한 Oracle DB접근_221021.pdf 파일 다운로드

Naver Blog

20221111 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 1111_training.R 파일 다운로드 # 베이지안 # 실습. # ================ install.packages("e1071") install.packages("caret") library(e1071) data <- read.csv(file = "heart.csv", header = T) head(data) str(data) library(caret) set.seed(1234) tr_data <- createDataPartition(y=data$AHD, p=0.7, list=FALSE) tr <- data[tr_data,] te <- data[-tr_data,] Bayes <- naiveBayes(AHD~. ,data=tr) Bayes predicted <- predict(Bayes, te, type="class") table(predicted, te$AHD) AHD <- as.factor(te$AHD) confusionMatrix(predicted, AH

Naver Blog

순환신경망

import numpy as np timesteps = 10 # 시점의 수. NLP에서는 보통 문장의 길이가 된다. input_size = 4 # 입력의 차원. NLP에서는 보통 단어 벡터의 차원이 된다. hidden_size = 8 # 은닉 상태의 크기. 메모리 셀의 용량이다. inputs = np.random.random((timesteps, input_size)) # 입력에 해당되는 2D 텐서 hidden_state_t = np.zeros((hidden_size,)) # 초기 은닉 상태는 0(벡터)로 초기화 # 은닉 상태의 크기 hidden_size로 은닉 상태를 만듬. print(hidden_state_t) # 8의 크기를 가지는 은닉 상태. 현재는 초기 은닉 상태로 모든 차원이 0의 값을 가짐. Wx = np.random.random((hidden_size, input_size)) # (8, 4)크기의 2D 텐서 생성. 입력에 대한 가중치. Wh = np.random.ran

Naver Blog

RNN_다대다

import torch import torch.nn as nn import torch.optim as optim import numpy as np input_str = 'apple' label_str = 'pple!' char_vocab = sorted(list(set(input_str+label_str))) vocab_size = len(char_vocab) print ('문자 집합의 크기 : {}'.format(vocab_size)) char_to_index = dict((c, i) for i, c in enumerate(char_vocab)) # 문자에 고유한 정수 인덱스 부여 print(char_to_index) index_to_char={} for key, value in char_to_index.items(): index_to_char[value] = key print(index_to_char) x_data = [char_to_index[c] for c in input_s

Naver Blog

R 연관분석

첨부파일 연관분석5_221114.pdf 파일 다운로드 첨부파일 12주차_연관성규칙.pdf 파일 다운로드

Naver Blog

RNN_문자단위

import torch import torch.nn as nn import torch.optim as optim import numpy as np sentence = ("if you want to build a ship, don't drum up people together to " "collect wood and don't assign them tasks and work, but rather " "teach them to long for the endless immensity of the sea.") char_set = list(set(sentence)) # 중복을 제거한 문자 집합 생성 char_dic = {c: i for i, c in enumerate(char_set)} # 각 문자에 정수 인코딩 print(char_dic) # 공백도 여기서는 하나의 원소 dic_size = len(char_dic) print('문자 집합의 크기 : {}'.format(dic_size)) #

Naver Blog

R 앙상블

첨부파일 앙상블5_221109.pdf 파일 다운로드 첨부파일 7 앙상블.pdf 파일 다운로드

Naver Blog

R 인공신경망

첨부파일 인공신경망_221110.pdf 파일 다운로드 첨부파일 10주차_신경망.pdf 파일 다운로드

Naver Blog

R 서포트백터머신

첨부파일 서포트벡터머신5_221110.pdf 파일 다운로드

Naver Blog

R 다차원척도법

첨부파일 다차원척도법5_221111.pdf 파일 다운로드

Naver Blog

Olracle SQL문 확장

첨부파일 오라클 SQL2_3_221018.pdf 파일 다운로드

Naver Blog

R 로지스틱 회귀분석

첨부파일 로지스틱 회귀분석_221104.pdf 파일 다운로드 첨부파일 9주차_로지스틱회귀분석.pdf 파일 다운로드

Naver Blog

R 시계열분석

첨부파일 시계열분석6_221107.pdf 파일 다운로드 첨부파일 sm_time_series.pdf 파일 다운로드 첨부파일 GGPLOT_시계열그래프.pdf 파일 다운로드

Naver Blog

R 의사결정나무

첨부파일 의사결정나무_221109.pdf 파일 다운로드

Naver Blog

R 주성분 분석

첨부파일 R_ch14 주성분 분석4_221101.pdf 파일 다운로드

Naver Blog

R 기초

첨부파일 R_ch1_R설치개요_220920.pdf 파일 다운로드 첨부파일 R ch1 연습문제_220921.pdf 파일 다운로드

Naver Blog

R 데이터유형과 구조

첨부파일 R_ch2_데이터유형과구조_220921.pdf 파일 다운로드 첨부파일 R ch2 연습문제2_220922.pdf 파일 다운로드

Naver Blog

R 데이터 입출력

첨부파일 R_ch3 데이터 입출력2_220923.pdf 파일 다운로드 첨부파일 R ch3 연습문제_220923.pdf 파일 다운로드

Naver Blog

R 제어문과 함수

첨부파일 R_ch4_제어문과함수4_220923.pdf 파일 다운로드 첨부파일 R ch4 연습문제_220926.pdf 파일 다운로드

Naver Blog

R 데이터 조작

첨부파일 R_ch6_데이터조작_220926.pdf 파일 다운로드 첨부파일 R ch6 데이터조작 연습문제_220927.pdf 파일 다운로드

Naver Blog

EDA와 DATA정제

첨부파일 R_ch7 EDA와 data정제_220928.pdf 파일 다운로드

Naver Blog

R 기술통계분석

첨부파일 R_ch11 기술통계분석_221013.pdf 파일 다운로드

Naver Blog

R 집단간 차이분석

첨부파일 R_ch13_집단간 차이분석_221025.pdf 파일 다운로드

Naver Blog

R 카이제곱검정

첨부파일 R_ch12_교차분석_카이제곱검정5_221031.pdf 파일 다운로드

Naver Blog

NPL

pip install konlpy from konlpy.tag import Okt okt = Okt() token = okt.morphs("나는 자연어 처리를 배운다") print(token) word2index = {} for voca in token: if voca not in word2index.keys(): word2index[voca] = len(word2index) print(word2index) def one_hot_encoding(word, word2index): one_hot_vector = [0]*(len(word2index)) index = word2index[word] one_hot_vector[index] = 1 return one_hot_vector one_hot_encoding("처리",word2index)

Naver Blog

워드임베딩

import torch # 원-핫 벡터 생성 dog = torch.FloatTensor([1, 0, 0, 0, 0]) cat = torch.FloatTensor([0, 1, 0, 0, 0]) computer = torch.FloatTensor([0, 0, 1, 0, 0]) netbook = torch.FloatTensor([0, 0, 0, 1, 0]) book = torch.FloatTensor([0, 0, 0, 0, 1]) print(torch.cosine_similarity(cat, cat, dim=0)) print(torch.cosine_similarity(cat, computer, dim=0)) print(torch.cosine_similarity(computer, netbook, dim=0)) print(torch.cosine_similarity(netbook, book, dim=0))

Naver Blog

20221110 빅데이터&AI(머신러닝,딥러닝)인공지능

첨부파일 11010_training.R 파일 다운로드 # 인공신경망 # 실습 (간단한 인공신경망 모델 생성) # 1단계: 패키지 설치 install.packages("nnet") library(nnet) # 2단계: 데이터 셋 생성 # 데이터프레임 생성 - 입력 변수(x)와 출력변수(y) df = data.frame( x2 = c(1:6), x1 = c(6:1), y = factor(c('no', 'no', 'no', 'yes', 'yes', 'yes')) ) str(df) # 3단계: 인공신경망 모델 생성 model_net = nnet(y ~ ., df, size = 1) # 4단계: 모델 결과 변수 보기 model_net # 5단계: 가중치(weights)보기 summary(model_net) # 6단계: 분류모델의 적합값 보기 model_net$fitted.values # 7단계: 분류모델의 예측치 생성과 분류 정확도 p <- predict(model_net, df, type

Naver Blog

nn.Embedding()

import torch train_data = 'you need to know how to code' # 중복을 제거한 단어들의 집합인 단어 집합 생성. word_set = set(train_data.split()) # 단어 집합의 각 단어에 고유한 정수 맵핑. vocab = {word: i+2 for i, word in enumerate(word_set)} vocab['<unk>'] = 0 vocab['<pad>'] = 1 print(vocab) # 단어 집합의 크기만큼의 행을 가지는 테이블 생성. embedding_table = torch.FloatTensor([ [ 0.0, 0.0, 0.0], [ 0.0, 0.0, 0.0], [ 0.2, 0.9, 0.3], [ 0.1, 0.5, 0.7], [ 0.2, 0.1, 0.8], [ 0.4, 0.1, 0.1], [ 0.1, 0.8, 0.9], [ 0.6, 0.1, 0.1]]) sample = 'you need to run'.split()

Naver Blog

Data loading, Storage

첨부파일 3.data_loading_n_storage_part_n1_220913.pdf 파일 다운로드

Naver Blog

Data Cleaning and Preparation

첨부파일 4.DataCleaning_Preparation_n1_220913.pdf 파일 다운로드

Naver Blog

Data Aggregation and Group Operations

첨부파일 6.data_aggregation_group_operations_n1_220913.pdf 파일 다운로드

1 2