tlswjdgns016의 등록된 링크

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

Naver Blog

합성곱신경망_심화.CNN

# 1번 레이어 : 합성곱층(Convolutional layer) 합성곱(in_channel = 1, out_channel = 32, kernel_size=3, stride=1, padding=1) + 활성화 함수 ReLU 맥스풀링(kernel_size=2, stride=2)) # 2번 레이어 : 합성곱층(Convolutional layer) 합성곱(in_channel = 32, out_channel = 64, kernel_size=3, stride=1, padding=1) + 활성화 함수 ReLU 맥스풀링(kernel_size=2, stride=2)) # 3번 레이어 : 합성곱층(Convolutional layer) 합성곱(in_channel = 64, out_channel = 128, kernel_size=3, stride=1, padding=1) + 활성화 함수 ReLU 맥스풀링(kernel_size=2, stride=2, padding=1)) # 4번 레이어 : 전결합층(Fu

Naver Blog

자연어처리_기초

en_text = "A Dog Run back corner near spare bedrooms" import spacy spacy_en = spacy.load('en_core_web_sm') def tokenize(en_text): return [tok.text for tok in spacy_en.tokenizer(en_text)] print(tokenize(en_text)) !pip install nltk import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize print(word_tokenize(en_text)) kor_text = "사과의 놀라운 효능이라는 글을 봤어. 그래서 오늘 사과를 먹으려고 했는데 사과가 썩어서 슈퍼에 가서 사과랑 오렌지 사왔어" print(kor_text.split()) !git clone https://github.com/SOMJANG/Mecab-ko-for-Google-Co

Naver Blog

인공신경망_손글씨분류하기

%matplotlib inline import matplotlib.pyplot as plt # 시각화를 위한 맷플롯립 from sklearn.datasets import load_digits digits = load_digits() # 1,979개의 이미지 데이터 로드 print(digits.images[0]) print(digits.target[0]) print('전체 샘플의 수 : {}'.format(len(digits.images))) images_and_labels = list(zip(digits.images, digits.target)) for index, (image, label) in enumerate(images_and_labels[:5]): # 5개의 샘플만 출력 plt.subplot(2, 5, index + 1) plt.axis('off') plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') plt.tit

Naver Blog

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

첨부파일 1109_training.R 파일 다운로드 # 실습 (의사결정 트리 생성: ctree()함수 이용) # 1단계: party패키지 설치 install.packages("party") library(party) # 2단계: airquality 데이터셋 로딩 library(datasets) str(airquality) # 3단계: formula생성 formula <- Temp ~ Solar.R + Wind + Ozone # 4단계: 분류모델 생성 – formula를 이용하여 분류모델 생성 air_ctree <- ctree(formula, data = airquality) air_ctree # 5단계: 분류분석 결과 plot(air_ctree) # 1단계: 학습데이터와 검정데이터 샘플링 #set.seed(1234) idx <- sample(1:nrow(iris), nrow(iris) * 0.7) train <- iris[idx, ] test <- iris[-idx, ] # 2단계:

Naver Blog

합성곱연산_CNN

# 1번 레이어 : 합성곱층(Convolutional layer) 합성곱(in_channel = 1, out_channel = 32, kernel_size=3, stride=1, padding=1) + 활성화 함수 ReLU 맥스풀링(kernel_size=2, stride=2)) # 2번 레이어 : 합성곱층(Convolutional layer) 합성곱(in_channel = 32, out_channel = 64, kernel_size=3, stride=1, padding=1) + 활성화 함수 ReLU 맥스풀링(kernel_size=2, stride=2)) # 3번 레이어 : 전결합층(Fully-Connected layer) 특성맵을 펼친다. # batch_size × 7 × 7 × 64 → batch_size × 3136 전결합층(뉴런 10개) + 활성화 함수 Softmax import torch import torch.nn as nn # 배치 크기 × 채널 × 높이(height) ×

Naver Blog

소프트맥스회귀_회귀의비용함수

import torch import torch.nn.functional as F torch.manual_seed(1) z = torch.FloatTensor([1, 2, 3]) hypothesis = F.softmax(z, dim=0) print(hypothesis) hypothesis.sum() z = torch.rand(3, 5, requires_grad=True) hypothesis = F.softmax(z, dim=1) print(hypothesis) y = torch.randint(5, (3,)).long() print(y) # 모든 원소가 0의 값을 가진 3 × 5 텐서 생성 y_one_hot = torch.zeros_like(hypothesis) y_one_hot.scatter_(1, y.unsqueeze(1), 1) print(y.unsqueeze(1)) cost = (y_one_hot * -torch.log(hypothesis)).sum(dim=1).mean() pr

Naver Blog

소프트맥스회귀_구현하기

import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) x_train = [[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2, 5, 6], [1, 6, 6, 6], [1, 7, 7, 7]] y_train = [2, 2, 2, 1, 1, 1, 0, 0] x_train = torch.FloatTensor(x_train) y_train = torch.LongTensor(y_train) print(x_train.shape) print(y_train.shape) torch.Size([8, 4]) torch.Size([8]) y_one_hot = torch.zeros(8, 3) y_one_hot.scatter_(1, y_train.unsqueeze(1), 1)

Naver Blog

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

첨부파일 1103_training.R 파일 다운로드 # 회귀분석 # 1단계: 데이터 가져오기 product <- read.csv("product.csv", header = TRUE) str(product) # 2단계: 독립변수와 종속변수 생성 y = product$제품_만족도 x = product$제품_적절성 df <- data.frame(x, y) # 3단계: 단순 선형회귀 모델 생성 result.lm <- lm(formula = y ~ x, data = df) # 4단계: 회귀분석의 절편과 기울기 result.lm # 5단계: 모델의 적합값과 잔차 보기 names(result.lm) # 5-1단계: 적합값 보기 fitted.values(result.lm)[1:2] # 5-2단계: 관측값 보기 head(df, 1) # 5-3단계: 회귀방정식을 적용하여 모델의 적합값 계산 Y = 0.7789 + 0.7393 * 4 Y # 5-4단계: 잔차(오차) 계산 3 - 3.735963 # 실습

Naver Blog

소프트맥스회귀_MINIST분류

for X, Y in data_loader: # 입력 이미지를 [batch_size × 784]의 크기로 reshape # 레이블은 원-핫 인코딩 X = X.view(-1, 28*28) import torch import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.utils.data import DataLoader import torch.nn as nn import matplotlib.pyplot as plt import random USE_CUDA = torch.cuda.is_available() # GPU를 사용가능하면 True, 아니라면 False를 리턴 device = torch.device("cuda" if USE_CUDA else "cpu") # GPU 사용 가능하면 사용하고 아니면 CPU 사용 print("다음 기기로 학습합니다:", device) # for re

Naver Blog

선형회귀_기초

import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) x_train = torch.FloatTensor([[1], [2], [3]]) y_train = torch.FloatTensor([[2], [4], [6]]) print(x_train) print(x_train.shape) print(y_train) print(y_train.shape) # 가중치 W를 0으로 초기화하고 학습을 통해 값이 변경되는 변수임을 명시함. W = torch.zeros(1, requires_grad=True) # 가중치 W를 출력 print(W) b = torch.zeros(1, requires_grad=True) print(b) hypothesis = x_train * W + b print(hypothesis) # 앞서 배운 torch.mean으로 평균

Naver Blog

선형회귀_자동미분

import torch w = torch.tensor(1.0, requires_grad=True) y = w**2 z = 2*y + 5 print(w) print(y) print(z) z.backward() print('수식을 w로 미분한 값 : {}'.format(w.grad))

Naver Blog

선형회귀_다중선형회귀

import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) # 훈련 데이터 x1_train = torch.FloatTensor([[73], [93], [89], [96], [73]]) x2_train = torch.FloatTensor([[80], [88], [91], [98], [66]]) x3_train = torch.FloatTensor([[75], [93], [90], [100], [70]]) y_train = torch.FloatTensor([[152], [185], [180], [196], [142]]) # 가중치 w와 편향 b 초기화 w1 = torch.zeros(1, requires_grad=True) w2 = torch.zeros(1, requires_grad=True) w3 = torch.zeros(1, requires

Naver Blog

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

첨부파일 1102_training.R 파일 다운로드 # 요인분석 # 프레임생성 s1 <- c(1, 2, 1, 2, 3, 4, 2, 3, 4, 5) s2 <- c(1, 3, 1, 2, 3, 4, 2, 4, 3, 4) s3 <- c(2, 3, 2, 3, 2, 3, 5, 3, 4, 2) s4 <- c(2, 4, 2, 3, 2, 3, 5, 3, 4, 1) s5 <- c(4, 5, 4, 5, 2, 1, 5, 2, 4, 3) s6 <- c(4, 3, 4, 4, 2, 1, 5, 2, 4, 2) name <- 1:10 subject <- data.frame(s1, s2, s3, s4, s5, s6) str(subject) # 주성분 분석으로 요인 수 알아보기 pc <- prcomp(subject) summary(pc) plot(pc) prcomp(subject) # 교유값으로 요인수 분석 en <- eigen(cor(subject)) names(en) en$values en$vectors plot

Naver Blog

선형회귀_nn.Module

import torch.nn as nn #model = nn.Linear(input_dim, output_dim) import torch.nn.functional as F #cost = F.mse_loss(prediction, y_train) import torch import torch.nn as nn import torch.nn.functional as F torch.manual_seed(1) # 데이터 x_train = torch.FloatTensor([[1], [2], [3]]) y_train = torch.FloatTensor([[2], [4], [6]]) # 모델을 선언 및 초기화. 단순 선형 회귀이므로 input_dim=1, output_dim=1. model = nn.Linear(1,1) print(list(model.parameters())) # optimizer 설정. 경사 하강법 SGD를 사용하고 learning rate를 의미하는 lr은 0.01 optimize

Naver Blog

선형회귀_클래스로파이토치

import torch import torch.nn as nn import torch.nn.functional as F # 모델을 선언 및 초기화. 단순 선형 회귀이므로 input_dim=1, output_dim=1. model = nn.Linear(1,1) class LinearRegressionModel(nn.Module): # torch.nn.Module을 상속받는 파이썬 클래스 def __init__(self): super().__init__() self.linear = nn.Linear(1, 1) # 단순 선형 회귀이므로 input_dim=1, output_dim=1. def forward(self, x): return self.linear(x) class MultivariateLinearRegressionModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(3, 1) # 다중 선형

Naver Blog

선형회귀_미니배치와데이터로드

import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset # 텐서데이터셋 from torch.utils.data import DataLoader # 데이터로더 x_train = torch.FloatTensor([[73, 80, 75], [93, 88, 93], [89, 91, 90], [96, 98, 100], [73, 66, 70]]) y_train = torch.FloatTensor([[152], [185], [180], [196], [142]]) dataset = TensorDataset(x_train, y_train) dataloader = DataLoader(dataset, batch_size=2, shuffle=True) model = nn.Linear(3,1) optimizer = torch.optim.SGD(model.paramet

Naver Blog

선형회귀_커스텀데이터셋

class CustomDataset(torch.utils.data.Dataset): def __init__(self): 데이터셋의 전처리를 해주는 부분 def __len__(self): 데이터셋의 길이. 즉, 총 샘플의 수를 적어주는 부분 def __getitem__(self, idx): 데이터셋에서 특정 1개의 샘플을 가져오는 함수 import torch import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader # Dataset 상속 class CustomDataset(Dataset): def __init__(self): self.x_data = [[73, 80, 75], [93, 88, 93], [89, 91, 90], [96, 98, 100], [73, 66, 70]] self.y_data = [[152], [185], [180], [196]

Naver Blog

로지스틱회귀_기초

%matplotlib inline import numpy as np # 넘파이 사용 import matplotlib.pyplot as plt # 맷플롯립사용 def sigmoid(x): # 시그모이드 함수 정의 return 1/(1+np.exp(-x)) x = np.arange(-5.0, 5.0, 0.1) y = sigmoid(x) plt.plot(x, y, 'g') plt.plot([0,0],[1.0,0.0], ':') # 가운데 점선 추가 plt.title('Sigmoid Function') plt.show() x = np.arange(-5.0, 5.0, 0.1) y1 = sigmoid(0.5*x) y2 = sigmoid(x) y3 = sigmoid(2*x) plt.plot(x, y1, 'r', linestyle='--') # W의 값이 0.5일때 plt.plot(x, y2, 'g') # W의 값이 1일때 plt.plot(x, y3, 'b', linestyle='--') # W의

Naver Blog

로지스틱회귀_nn.Module

import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] y_data = [[0], [0], [0], [1], [1], [1]] x_train = torch.FloatTensor(x_data) y_train = torch.FloatTensor(y_data) model = nn.Sequential( nn.Linear(2, 1), # input_dim = 2, output_dim = 1 nn.Sigmoid() # 출력은 시그모이드 함수를 거친다 ) model(x_train) # optimizer 설정 optimizer = optim.SGD(model.parameters(), lr=1) nb_epochs = 1000 for epoch in

Naver Blog

로지스틱회귀_클래스로파이토치

import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] y_data = [[0], [0], [0], [1], [1], [1]] x_train = torch.FloatTensor(x_data) y_train = torch.FloatTensor(y_data) class BinaryClassifier(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(2, 1) self.sigmoid = nn.Sigmoid() def forward(self, x): return self.sigmoid(self.linear(x)) model = BinaryClassifier

Naver Blog

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

첨부파일 1021_SQL.py 파일 다운로드 첨부파일 1021_SQL.R 파일 다운로드 import cx_Oracle import os # 한글 지원 환경 os.putenv('NLS_LANG', '.UTF8') # Path 설정 LOCATION = r"C:/instantclient_21_7" os.environ["PATH"] = LOCATION + ";" + os.environ["PATH"] # DB 연결 connect = cx_Oracle.connect("scott", "tiger", "localhost:1521/xe") cs = connect.cursor() # 데이터 추가(insert) sql = "insert into py_table values('kang', '1234', '강감찬', 45)" cs.execute(sql) # SQL 문 cs.execute("select * from py_table") # SQL 문 for i in cs: # data 보기 print(i) #

Naver Blog

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

첨부파일 R과 python을 이용한 Oracle DB접근_221021.pdf 파일 다운로드 1 R과 python으로 Oracle DB에 접근 1. R R에서 DB에 연결 https://db.rstudio.com/getting-started/connect-to-database # Ch9 Oracle DB # R 3.6.3 # 사전작업 # # 1. C:드라이브에 OracleTest 폴더 생성 # 2. OracleTest폴더에 driver ojdbc6 저장 # ojdbc6 위치 # C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib # 3. SQL developer에서 scott계정으로 table 생성 # # create table test_table( # id varchar(50) primary key, # pass varchar(30) not null, # name varchar(25) not null, # age number(2) # );

Naver Blog

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

첨부파일 R_ch13_집단간 차이분석_221025.pdf 파일 다운로드 # 전체 표본 크기(N): 10,000명 # 표본 평균(X): 165.1cm # 표본 표준편차(S): 2cm N = 10000 X = 165.1 S = 2 low <- X -1.96 * S / sqrt(N) high <- X + 1.96 * S / sqrt(N) low; high # 실습 (신뢰구간으로 표본오차 구하기) high - X (low - X) * 100 (high - X) * 100 # 1단계: 실습 데이터 가져오 setwd("C:/Rwork/ ") data <- read.csv("one_sample.csv", header = TRUE) head(data) x <- data$survey # 2단계: 빈도수와 비율계산 summary(x) length(x) table(x) # 3단계: 패키지를 이용하여 빈도수와 비율 계산 install.packages("prettyR") library(prettyR) fr

Naver Blog

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

첨부파일 1026_training.R 파일 다운로드 통계 # SJH # 1. 교육 방법에 따라 시험성적에 차이가 있는지 검정하시오 # (힌트. 두 집단 평균 차이 검정) # 1) 데이터셋: twomethod.csv # 2) 변수: method(교육방법), score(시험성적) # 3) 모델: 교육방법(명목) -> 시험성적(비율) # 4) 전처리, 결측치 제거 setwd("C:/Rwork/ ") data <- read.csv("twomethod.csv", header = TRUE) head(data) data<- na.omit(data) #na 제거 a <- subset(data, method ==1) b <- subset(data, method ==2) a <- a$score b <- b$score #동절성 확인 var.test(a, b) #두 집단 평균 차이 검정(양측검정) t.test(a, b, altr = "two.sided", conf.int = TRUE, conf.level

Naver Blog

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

첨부파일 비모수검정.pdf 파일 다운로드

Naver Blog

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

adsp 자격증 공부 첨부파일 Eduatoz_ADsP_1과목_데이터의_이해_220226.pdf 파일 다운로드 첨부파일 Eduatoz_ADsP_2과목_데이터_분석_기획_220228.pdf 파일 다운로드 첨부파일 Eduatoz_ADsP_3과목_PART1_R_220425.pdf 파일 다운로드 첨부파일 Eduatoz_ADsP_3과목_PART2_01_220228.pdf 파일 다운로드 첨부파일 Eduatoz_ADsP_3과목_PART2_02_기초통계분석_시계열분석_220228.pdf 파일 다운로드 첨부파일 Eduatoz_ADsP_3과목_PART3_정형데이터마이닝_220505.pdf 파일 다운로드

Naver Blog

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

첨부파일 R_ch12_교차분석_카이제곱검정5_221031.pdf 파일 다운로드 # SJH library(ggplot2) library(gmodels) # 1. 직업 유형에 따른 응답 정도에 차이가 있는가를 단계별로 검정하시오 (동질성 검정) # 1) 파일 가져오기 data <- read.csv("Response.csv") # 2) 코딩변경 - 리코딩 data$job1[data$job == 1] <- "학생" data$job1[data$job == 2] <- "직장인" data$job1[data$job == 3] <- "주부" data$response1[data$response == 1] <- "무응답" data$response1[data$response == 2] <- "낮음" data$response1[data$response == 1] <- "높음" # 3) 교차 분할표 작성 x <- data$job1 y <- data$response1 table(x, y) # 4) 동질성 검정

Naver Blog

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

첨부파일 1101_training.R 파일 다운로드 # 상관분석 # 데이터가져오기 product <- read.csv("C:/Rwork/product.csv", header = TRUE) head(product) # 기술통계량 summary(product) sd(product$제품_친밀도); sd(product$제품_적절성); sd(product$제품_만족도) # 1단계: 변수 간의 상관계수 보기 cor(product$제품_친밀도, product$제품_적절성) cor(product$제품_친밀도, product$제품_만족도) # 2단계: 제품_적절성과 제품_만족도의 상관계수 보기 cor(product$제품_적절성, product$제품_만족도) # 3단계: (제품_적절성+제품_친밀도)와 제품_만족도의 상관계수 보기 cor(product$제품_적절성 + product$제품_친밀도, product$제품_만족도) install.packages("corrgram") library(corrgra

Naver Blog

텐서조작2

import numpy as np import torch t = np.array([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]) ft = torch.FloatTensor(t) print(ft.shape) print(ft.view([-1, 3])) # ft라는 텐서를 (?, 3)의 크기로 변경 print(ft.view([-1, 3]).shape) print(ft.view([-1, 1, 3])) print(ft.view([-1, 1, 3]).shape) ft = torch.FloatTensor([[0], [1], [2]]) print(ft) print(ft.shape) print(ft.squeeze()) print(ft.squeeze().shape) ft = torch.Tensor([0, 1, 2]) print(ft.shape) print(ft.unsqueeze(0)) # 인덱스가 0부터 시작하므로 0은 첫번째 차원을 의미한다. print(f

Naver Blog

텐서조작하기

import numpy as np t = np.array([0., 1., 2., 3., 4., 5., 6.]) # 파이썬으로 설명하면 List를 생성해서 np.array로 1차원 array로 변환함. print(t) print('Rank of t: ', t.ndim) print('Shape of t: ', t.shape) print('t[0] t[1] t[-1] = ', t[0], t[1], t[-1]) # 인덱스를 통한 원소 접근 print('t[2:5] t[4:-1] = ', t[2:5], t[4:-1]) # [시작 번호 : 끝 번호]로 범위 지정을 통해 가져온다. print('t[:2] t[3:] = ', t[:2], t[3:]) # 시작 번호를 생략한 경우와 끝 번호를 생략한 경우 t = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.], [10., 11., 12.]]) print(t) print('Rank of t: ', t.ndim

Naver Blog

파이썬클래스

import torch result = 0 def add(num): global result result += num return result print(add(3)) print(add(4)) result1 = 0 result2 = 0 def add1(num): global result1 result1 += num return result1 def add2(num): global result2 result2 += num return result2 print(add1(3)) print(add1(4)) print(add2(3)) print(add2(7)) class Calculator: def __init__(self): # 객체 생성 시 호출될 때 실행되는 초기화 함수. 이를 생성자라고 한다. self.result = 0 def add(self, num): # 객체 생성 후 사용할 수 있는 함수. self.result += num return self.result cal1 = Calc

Naver Blog

프로그래머스 레벨 1 [하샤드 수] _ python(파이썬)

문제 설명 양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요. 제한 조건 x는 1 이상, 10000 이하인 정수입니다. 입출력 예 arr return 10 true 12 true 11 false 13 false 입출력 예 설명 입출력 예 #1 10의 모든 자릿수의 합은 1입니다. 10은 1로 나누어 떨어지므로 10은 하샤드 수입니다. 입출력 예 #2 12의 모든 자릿수의 합은 3입니다. 12는 3으로 나누어 떨어지므로 12는 하샤드 수입니다. 입출력 예 #3 11의 모든 자릿수의 합은 2입니다. 11은 2로 나누어 떨어지지 않으므로 11는 하샤드 수가 아닙니다. 입출력 예 #4 13의 모든 자릿수의 합은 4입니다. 13은 4로 나누어 떨어지지 않으므로 13은 하

Naver Blog

프로그래머스 레벨 1 [정수 내림차순으로 배치하기] _ python(파이썬)

문제 설명 함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다. 제한 조건 n은 1이상 8000000000 이하인 자연수입니다. 입출력 예 n return 118372 873211 정답 def solution(n): answer = [] for i in str(n): answer.append(i) answer.sort(reverse=True) answer =''.join(answer) answer = int(answer) return answer 실행 결과 채점을 시작합니다. 정확성 테스트 테스트 1 〉 통과 (0.02ms, 10.4MB) 테스트 2 〉 통과 (0.02ms, 10.3MB) 테스트 3 〉 통과 (0.02ms, 10.4MB) 테스트 4 〉 통과 (0.02ms, 10.4MB) 테스트 5 〉 통과 (0.02ms, 10.4MB) 테스트

Naver Blog

프로그래머스 레벨 1 [콜라츠] _ python(파이썬)programmers_level1

문제 설명 1937년 Collatz란 사람에 의해 제기된 이 추측은, 주어진 수가 1이 될 때까지 다음 작업을 반복하면, 모든 수를 1로 만들 수 있다는 추측입니다. 작업은 다음과 같습니다. 1-1. 입력된 수가 짝수라면 2로 나눕니다. 1-2. 입력된 수가 홀수라면 3을 곱하고 1을 더합니다. 2. 결과로 나온 수에 같은 작업을 1이 될 때까지 반복합니다. 예를 들어, 주어진 수가 6이라면 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 이 되어 총 8번 만에 1이 됩니다. 위 작업을 몇 번이나 반복해야 하는지 반환하는 함수, solution을 완성해 주세요. 단, 주어진 수가 1인 경우에는 0을, 작업을 500번 반복할 때까지 1이 되지 않는다면 –1을 반환해 주세요. 제한 사항 입력된 수, num은 1 이상 8,000,000 미만인 정수입니다. 입출력 예 n result 6 8 16 4 626331 -1 입출력 예 설명 입출력 예 #1 문제의 설명과 같습니다.

Naver Blog

20221017 국비지원 리뷰!

첨부파일 오라클 SQL1_8_221017.pdf 파일 다운로드 첨부파일 scott1.sql 파일 다운로드 commit; desc salesman; create table board ( num number(4), title varchar2(30), author varchar2(12), content varchar2(600), writeday date default sysdate ); desc board; alter table salesman add (sal number(7, 2)); desc salesman; alter table salesman modify (sal number(10, 2)); desc salesman; alter table salesman drop (sal); desc salesman; drop table salesman; select * from tab; show recyclebin; flashback table salesman to before drop; se

Naver Blog

20221018 국비지원 리뷰!

첨부파일 오라클 SQL2_3_221018.pdf 파일 다운로드 첨부파일 scott2.sql 파일 다운로드 select avg(sal) from emp group by deptno; select max(sal) from emp group by deptno having max(sal) > 500; create table myboard ( num number(4) primary key, author varchar2(12), title varchar2(30), content varchar2(60) ); create sequence myboard_seq; insert into myboard(num, author, title, content) values(myboard_seq.nextval, '전우치', '제목','내용이다.'); select * from emp, dept; select empno, ename, sal, dept.deptno from emp, dept where emp.dept

Naver Blog

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

첨부파일 1019.sql 파일 다운로드 첨부파일 오라클 SQL2_3_221018.pdf 파일 다운로드 set serveroutput on; begin dbms_output.put_line('안녕 PL/SQL'); end; / -- 화면 출력기능을 활성화한다. set serveroutput on; -- 스칼라 변수를 선언한다. declare sonno number(4); sonname varchar2(12); -- 실행문을 시작한다. begin sonno := 1001; sonname := '홍길동'; dbms_output.put_line(' 사번 이름'); dbms_output.put_line(' ---------------'); dbms_output.put_line(' ' || sonno || ' ' || sonname); -- 실행문을 종료한다. end; / -- 화면 출력기능을 활성화한다. set serveroutput on; -- 레퍼런스 변수를 선언한다. declare so

Naver Blog

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

첨부파일 1020.sql 파일 다운로드 -- 저장 프로시저에 사용할 테이블을 emp 테이블에서 복사한다. create table empcopy as select*from emp; / -- 생성한 테이블의 정보를 조회한다. select * from empcopy; / -- 저장 프로시저를 생성한다. create or replace procedure del_all is begin -- empcopy 테이블의 저장된 데이터를 삭제한다. delete from empcopy; -- 트랜잭션 작업이 성공하여 완료한다. commit; end; / -- 저장 프로시저를 실행하여 empcopy 테이블에 저장된 데이터를 삭제한다. execute del_all; / -- 저장 프로시저에 대한 실행을 확인한다. select * from empcopy; / -- user_source 시스템 테이블의 구조를 확인한다. desc user_source; -- 저장 프로시저의 코드를 확인한다. select nam

Naver Blog

프로그래머스 레벨 1 [약수의 합] _ python(파이썬)

문제 설명 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요. 제한 사항 n은 0 이상 3000이하인 정수입니다. 입출력 예 n return 12 28 5 6 입출력 예 설명 입출력 예 #1 12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28입니다. 입출력 예 #2 5의 약수는 1, 5입니다. 이를 모두 더하면 6입니다. 정답 def solution(n): answer = [] for i in range(1, n+1): if (n % i == 0) : answer.append(i) answer = sum(answer) return answer 실행 결과 테스트 1 입력값 〉 12 기댓값 〉 28 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 5 기댓값 〉 6 실행 결과 〉 테스트를 통과하였습니다. 테스트 결과 (~˘˘)~ 2개 중 2개 성공

Naver Blog

20221013 국비지원 리뷰!

첨부파일 11.pdf 파일 다운로드 첨부파일 12.pdf 파일 다운로드 첨부파일 13.pdf 파일 다운로드

Naver Blog

프로그래머스 레벨 1 [자릿수 더하기]_ python(파이썬)

문제 설명 자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요. 예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다. 제한사항 N의 범위 : 100,000,000 이하의 자연수 입출력 예 N answer 123 6 987 24 입출력 예 설명 입출력 예 #1 문제의 예시와 같습니다. 입출력 예 #2 9 + 8 + 7 = 24이므로 24를 return 하면 됩니다. 정답 def solution(n): answer = 0 word = str(n) for i in range(len(word)): answer += int(word[i]) return answer 실행 결과 테스트 1 입력값 〉 123 기댓값 〉 6 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 987 기댓값 〉 24 실행 결과 〉 테스트를 통과하였습니다. 테스트 결과 (~˘˘)~ 2개 중 2개 성공

Naver Blog

20221013 국비지원 리뷰!

# Ch11 기술통계분석 # 1.1 빈도분석 # 빈도분석(Frequency Analysis) # 명목척도 또는 서열척도 같은 범주형 데이터를 대상으로 비율을 측정하는데 주로 이용 # 명목척도: 명목상 의미 없는 수치로 표현. 예) 거주지역, 성별 # 서열척도: 계급 순위를 수치로 표현. 예) 직급, 학력 수준 # 빈도수, 비율 등으로 나타냄 # 1.2 기술통계분석 # 등간척도나 비율척도와 같은 연속적 데이터를 분석할 때 이용 # 등간척도: 속성의 간격이 일정한 값을 갖는 변수. 예) 만족도 조사의 보기 # 비율척도: 등간척도의 특성에 절대 원점이 존재하는 척도. 0을 기준으로 한 수치. # 사칙연산이 가능. 예) 성적, 나이, 수량, 길이, 금액 # 2. 척도별 기술통계량 구하기 # 실습 (전체 데이터 셋의 특성 보기) # 1단계: 데이터 셋 가져오기 setwd("C:/Rwork/ ") data <- read.csv("descriptive.csv", header = TRUE) hea

Naver Blog

프로그래머스 레벨 1 [정수 제곱근 판별] _ python(파이썬)

문제 설명 임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다. n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요. 제한 사항 n은 1이상, 50000000000000 이하인 양의 정수입니다. 입출력 예 n return 121 144 3 -1 입출력 예 설명 입출력 예#1 121은 양의 정수 11의 제곱이므로, (11+1)를 제곱한 144를 리턴합니다. 입출력 예#2 3은 양의 정수의 제곱이 아니므로, -1을 리턴합니다. 정답 def solution(n): answer = 0 number = n ** 0.5 if number == int(number): answer = (number+1)**2 else : answer = -1 return answer 테스트 1 입력값 〉 121 기댓값 〉 144 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 3 기댓값

Naver Blog

20221014 국비지원 리뷰!

첨부파일 1014.sql 파일 다운로드 첨부파일 데이터베이스_SQL1_6_221014.pdf 파일 다운로드 desc emp; select * from tab; select username from all_users; select empno, ename, hiredate from emp where lower(ename) ='ford'; select empno, ename, hiredate from emp where ename =upper('ford'); select deptno, initcap(dname), initcap(loc) from dept where deptno = 10; select deptno, dname, concat(deptno, dname) from dept where deptno = 10; select substr(ename, 1, 2) from emp; select deptno, dname, length(dname) from dept where deptno = 1

Naver Blog

프로그래머스 레벨 1 [자연수 뒤집어 배열로 만들기] _ python(파이썬)

문제 설명 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다. 제한 조건 n은 10,000,000,000이하인 자연수입니다. 입출력 예 n return 12345 [5,4,3,2,1] 정답 def solution(n): answer = [] for i in str(n): answer.append(i) answer = list(map(int,answer)) answer.sort(reverse=True) return answer 실행 결과 테스트 1 입력값 〉 12345 기댓값 〉 [5, 4, 3, 2, 1] 실행 결과 〉 테스트를 통과하였습니다. 테스트 결과 (~˘˘)~ 1개 중 1개 성공

Naver Blog

프로그래머스 레벨 1 [문자열 내 p와 y의 개수] _ python(파이썬)

문제 설명 대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요. 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다. 예를 들어 s가 "pPoooyY"면 true를 return하고 "Pyy"라면 false를 return합니다. 제한사항 문자열 s의 길이 : 50 이하의 자연수 문자열 s는 알파벳으로만 이루어져 있습니다. 입출력 예 s answer "pPoooyY" true "Pyy" false 입출력 예 설명 입출력 예 #1 'p'의 개수 2개, 'y'의 개수 2개로 같으므로 true를 return 합니다. 입출력 예 #2 'p'의 개수 1개, 'y'의 개수 2개로 다르므로 false를 return 합니다. 정답 def solution(s): s = s.lower() if s.co

Naver Blog

20221007 국비지원 리뷰!

R code에 기반한 2021년 코로나 데이터 분석 2022.10.14 A2팀(신정훈, 조아진, 임성구, 조성운) 목차 1. 분석 개요 2. 팀원 간 의견 수렴 3. 데이터 전처리 및 분석 3.1 전처리 과정 3.2 문제풀이 4. 검증 4.1 음수 데이터 원인 4.2 NaN 값 원인 4.3가설 검증 5. 결론 6. 별첨 1. 분석 개요 - 제공된 데이터셋은 Johns’ Hopkins 대학 내 The Center For Systems Science and Engineering(CSSE) 에서 업데이트하는 전 세계 코로나 (COVID-19) 발생 현황 데이터셋이다. 제공된 데이터셋 중 2021년 일간 데이터에서 python code로 다음을 수행하고 결과를 팀별로 리포트하시오. 1.1 일별 국가별 코로나 발생자 수와 사망자 수를 기준으로 전처리하시오. 일부 국가는 지역별로 코로나 발생자 수와 사망자 수가 분리되어 있으니 국가별로 집계하고 국가, 총발생자 수, 총사망자 수, 일평균 발생자

Naver Blog

20221011 국비지원 리뷰!

첨부파일 [정답] 2020 개념쎈 확통.pdf 파일 다운로드

Naver Blog

프로그래머스 레벨 1 [짝수와 홀수] _ python(파이썬

짝수와 홀수 문제 설명 정수 num이 짝수일 경우 "Even"을 반환하고 홀수인 경우 "Odd"를 반환하는 함수, solution을 완성해주세요. 제한 조건 num은 int 범위의 정수입니다. 0은 짝수입니다. 입출력 예 num return 3 "Odd" 4 "Even" 정답 def solution(num) : if num%2 != 0 : return "Odd" elif num%2 == 0 : return "Even" 주의상항 문제에서 반환을 요청시 retrun으로 해야하고 출력시 print를 사용 실행 결과 테스트 1 입력값 〉 3 기댓값 〉 "Odd" 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 4 기댓값 〉 "Even" 실행 결과 〉 테스트를 통과하였습니다. 테스트 결과 (~˘˘)~ 2개 중 2개 성공

Naver Blog

프로그래머스 레벨 1 [평균 구하기] _ python(파이썬

문제 설명 정수를 담고 있는 배열 arr의 평균값을 return하는 함수, solution을 완성해보세요. 제한사항 arr은 길이 1 이상, 100 이하인 배열입니다. arr의 원소는 -10,000 이상 10,000 이하인 정수입니다. 입출력 예 arr return [1,2,3,4] 2.5 [5,5] 5 정답 def solution(arr): answer = sum(arr)/len(arr) return answer 실행 결과 테스트 1 입력값 〉 [1, 2, 3, 4] 기댓값 〉 2.5 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 [5, 5] 기댓값 〉 5.0 실행 결과 〉 테스트를 통과하였습니다. 테스트 결과 (~˘˘)~ 2개 중 2개 성공

Naver Blog

covid 포토폴리오[python]

첨부파일 A1팀 보고서.docx 파일 다운로드 첨부파일 A1_SJH.py 파일 다운로드 # 0920_covid SJH import numpy as np import pandas as pd text = pd.read_csv(r'C:\Users\tj-bu\PycharmProjects\pythonProject\csse_covid_19_daily_reports\12-31-2020.csv') textt = pd.read_csv(r'C:\Users\tj-bu\PycharmProjects\pythonProject\csse_covid_19_daily_reports\12-31-2021.csv') text1 = text.groupby('Country_Region')['Confirmed', 'Deaths', 'Recovered', 'Active'].sum() textt1 = textt.groupby('Country_Region')['Confirmed', 'Deaths', 'Recovered', 'Act

Naver Blog

20221005 국비지원 리뷰!

첨부파일 8.pdf 파일 다운로드 첨부파일 9.pdf 파일 다운로드

Naver Blog

20221006 국비지원 리뷰!

첨부파일 R 문제 _신정훈.R 파일 다운로드 # 신정훈 # [문항1] * 아래 문제를 R code로 작성하여 제출하시오. # 다음은 학생별 과목별 시험 점수이다. Data를 대상으로 # 데이터프레임을 생성하고, 그 데이터프레임을 사용하고apply()를 # 적용하여 행/열 방향으로 조건에 맞게 통계량을 구하시오. library(dplyr) # 1) 3명 의사의 과목점수를 이용하여 데이터프레임(DataFrame)을 # 생성하여 화면출력하시오. Yoon <- c(95,83,75) Ahn <- c(85,95,60) Lee <- c(70,80,95) Data <- data.frame(Yoon,Ahn,Lee) rownames(Data) <- c('국어(Kor)','영어(Eng)','수학(Mat)') colnames(Data) <- c('윤봉길(Yoon)','안중근(Ahn)','이봉창(Lee)') Data apply(Data[3,],1,mean) # 3) 윤봉길의사의 과목 평균점수를 구하시오.

Naver Blog

20220927 국비지원 리뷰!

첨부파일 0927_training.R 파일 다운로드 # 0927_training # 1.8 집단변수 대상 그룹화 # 데이터 셋 내 범주형 컬럼을 대상으로 그룹화하는 group_by()함수 사용 # 형식: group_by(dataframe, 집단변수) # group_by 함수에 객체를 지정하면 컬럼별로 분리한다. # 컬럼의 집단별 평균 요약 통계량 # 컬럼의 집단별 평균에 대한 요약 통계량을 반환한다. # Ex. library(dplyr) csvgrade <- read.csv("grade_csv.csv") csvgrade %>% group_by(class) %>% summarise(mean_math = mean(math)) # group_by 함수는 인자로 범주형 변수가 포함된 컬럼명을 인자로 받아 요약 통계량을 # 계산 # 컬럼의 집단별 다중 요약 통계량 # 컬럼의 집단별 다중 요약 통계량을 반환한다. # Ex. library(dplyr) csvgrade <- read.csv("gr

Naver Blog

20220928 국비지원 리뷰!

첨부파일 0928_training.R 파일 다운로드 # Ch7 EDA와 data정제 # 데이터 전처리(data preprocessing) 과정 # 1. EDA란? # 탐색적 자료분석(Exploratory Data Analysis): # - 수집한 자료를 다양한 각도에서 관찰하고 이해하는 과정 # - 그래프나 통계적 방법을 이용하여 자료를 직관적으로 파악하는 과정 # 1.1 EDA 필요성 # 자료의 분포와 통계 파악 자료의 특성 이해 # 잠재적인 문제 발견 기존의 가설 수정 또는 새로운 방향의 가설 설정 # 1.2 EDA 과정 # 단계별 EDA 수행과정 # 1. 분석의 목적과 변수의 특징 확인 # 2. 자료 확인 및 전처리: 결측치, 이상치 # 3. 자료의 각 변수 관찰: 통계조사, 시각화 # 4. 변수 간의 관계에 초점을 맞춰 패턴 발견: 상관관계, 시각화 도구로 변수간의 패턴 발 # 견 # 2. 수집자료 이해 # 수집된 자료를 이해하는 단계 # 예) 자료구조, 관측치의 길이,

Naver Blog

20220929 국비지원 리뷰!

첨부파일 1.pdf 파일 다운로드 첨부파일 2.pdf 파일 다운로드 첨부파일 3.pdf 파일 다운로드 첨부파일 4.pdf 파일 다운로드 첨부파일 5.pdf 파일 다운로드 첨부파일 6.pdf 파일 다운로드

Naver Blog

20220922 국비지원 리뷰!

첨부파일 0922_training.R 파일 다운로드 rm(list=is()) ch.2 데이터 유형과 구조 R에서 제공하는 자료구조 1) Vector (1차원 배열) 2) Matrix (2차원 배열) 3) Array (다차원 배열) 4) Data Frame (2차원 테이블 구조) 5) List (자료구조 중첩) 1. Vector자료구조 index로 접근 가능 1.1 벡터 객체 벡터데이터 생성: c(), seq(), rep()함수 이용 c()함수 인수는 콜론(:)이나 콤마(,)를 이용하여 표현 콜론(:): 범위 콤마(,): 개별 데이터 구분 실습 (c()함수 이용 벡터 생성) c()함수 https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/c # 실습: c() 함수를 이용한 벡터 객체 생성 c(1:20) 1:20 c(1, 2, 3, 4, 5) 실습 (seq()함수 이용 벡터 생성) seq()함수 https://www.rd

Naver Blog

20220923 국비지원 리뷰!

첨부파일 0923_training.R 파일 다운로드 # 0923_taraining # Ch03 데이터 입출력 # 1. 데이터 불러오기 # 1.1 키보드 입력 # scan()함수, edit()함수 # (1) scan()함수 이용 # 실습 (키보드로 숫자 입력) # scan() 함수를 실행하면 console창에 입력 데이터의 순서를 나타내는 프롬프트가 표시 # 입력된 데이터는 입력된 순서대로 벡터변수에 저장됨 num <- scan() num sum(num) # 실습 (키보드로 문자 입력) # 키보드로 문자 입력을 위해서 scan()함수에서 ‘what=character()’를 사용 name <- scan(what = character()) name # (2) edit() 함수를 이용한 입력 # edit()함수는 표 형식의 데이터편집기를 제공 # 실습 (편집기를 이용한 data.frame 만들기) df = data.frame() df = edit(df) df # * Mac에서는 미동작 #

Naver Blog

20220926 국비지원 리뷰!

# 09226_t# 09226_training # 4.5 몬테카를로 시뮬레이션 함수 정의 # 몬테카를로 시뮬레이션은 현실적으로 불가능한 문제의 해답을 얻기 위해 난수의 확률 # 분포를 이용하는 모의 시험으로 근사적 해를 구하는 기법 # 실습 (동전 앞면과 뒷면에 대한 난수 확률분포의 기대확률 모의시험) # 동전 앞면과 뒷면의 난수 확률분포 함수 정의 coin <- function(n) { r <- runif(n, min = 0, max = 1) result <- numeric() for(i in 1:n) { if(r[i] <= 0.5) result[i] <- 0 else result[i] <- 1 } return(result) } # 동전 던지기 횟수가 10회인 경우 앞면(0)과 뒷면(1)이 나오는 vector 값 coin(10) # 몬테카를로 시뮬레이션 함수 정의 montaCoin <- function(n) { cnt <- 0 for(i in 1:n) { cnt <- cnt + c

Naver Blog

20220919 국비지원 리뷰!

# 0919_training # pandas import numpy as np import pandas as pd ''' fillna 메서드를 사용해서 누락된 값을 채우는 것은 값 치환 작업이라 볼 수 있음 map 메서드는 한 객체 안에서 값의 부분집합을 변경하는데 사용 ''' # replace 메서드는 같은 작업을 간단하고 유연한 방법 제공 data = pd.Series([1., -999., 2., -999., -1000., 3.]) data # -999 는 누락된 데이터를 나타내기 위한 값 # replace 메서드를 이용하여 NA 값으로 치환한 새로운 Series 생성 data.replace(-999, np.nan) # 여러 개의 값을 한 번에 치환하려면 하나의 값 대신 치환하려는 값의 리스트 사용 data.replace([-999, -1000], np.nan) # 치환하려는 값마다 다른 값으로 치환하려면 누락된 값 대신 새로 지정할 값의 리스트 사용 data.replace([-

Naver Blog

20220920 국비지원 리뷰!

# 0920_training import pandas as pd import numpy as np # 10.1.3 Grouping with Dicts and Series # 그룹 정보는 배열이 아닌 형태로 존재하기도 한다. # DataFrame 예제 people = pd.DataFrame(np.random.randn(5, 5), columns=['a', 'b', 'c', 'd', 'e'], index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis']) people.iloc[2:3, [1, 2]] = np.nan # Add a few NA values people # 각 컬럼을 나타낼 그룹 목록이 있고 그룹별로 컬럼의 값을 모두 더하는 경우 mapping = {'a': 'red', 'b': 'red', 'c': 'blue', 'd': 'blue', 'e': 'red', 'f' : 'orange'} # dict 에서 groupby 메서드로 배열을 추출할 수 있지만

Naver Blog

20220921 국비지원 리뷰!

# 0921_raining a <- 5 a <- 5 b <- 10 a <- 10 #사용설명 print(a,b) dim(available.packages()) a <- available.packages() head(a) install.packages("stringr") library(stringr) remove.packages("stringr") data() # 기본데이 셋 보기 hist(Nile) hist(Nile,freq = F) lines(density(Nile)) #working directory getwd() setwd('c:/users/tj-bu/Documents') getwd() # 변수이름 명명 방법 # (1) 변수 이름 명명 규칙 in R # 1) 첫 글자는 영문자로 시작 # 2) 2 번째 단어부터는 숫자, _, . 등을 사용 가능 # 3) 대문자와 소문자를 구별한다. # 4) 변수의 이름은 의미에 맞도록 작성한다. # 5) 한 번 정의된 변수는 재사용이 가능하고, 가

Naver Blog

20220916 국비지원 리뷰!

첨부파일 0916_training.py 파일 다운로드 # 0916_training # pandas # pandas 객체에 Numpy 의 유니버설 함수(배열의 각 원소에 적용되는 메서드) 적용 가능 import pandas as pd import numpy as np frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon']) frame np.abs(frame) # 자주 사용되는 또 다른 연산은 각 컬럼이나 로우의 1 차원 배열에 함수를 적용하는 것 # DataFrame 의 apply 메서드 사용 f = lambda x: x.max() - x.min() # 최대값 - 최소값 frame.apply(f) # apply 함수에 axis = 'columns' 설정시 각 로우에 대해 한 번씩만 수행 frame.apply(f, axis='columns') # 배열에

Naver Blog

20220914 국비지원 리뷰!

# 0915_training # Numpy import numpy as np # --> '벡터화' : 같은 크기의 배열 간의 산술 연산은 배열의 각 원소 단위로 적용 arr = np.array([[1., 2., 3.], [4., 5., 6.]]) arr arr * arr arr - arr # 스칼라 인자가 포함된 산술 연산의 경우 배열 내의 모든 원소에 스칼라 인자가 적용된다. 1 / arr arr ** 0.5 # 같은 크기를 가지는 배열 간의 비교 연산은 불리언 배열을 반환 arr2 = np.array([[0., 4., 1.], [7., 2., 12.]]) arr2 arr2 > arr # 브로드캐스팅(broadcasting): 크기가 다른 배열 간의 연 arr = np.arange(10) arr arr[5] arr[5:8] arr[5:8] = 12 arr # arr 배열의 슬라이스 생성 arr_slice = arr[5:8] arr_slice # arr_slice 의 값을 변경하면

Naver Blog

20220915 국비지원 리뷰!

# 0915_training # pandas import pandas as pd # Series 와 DataFrame 은 로컬 네임스페이스로 인포트 from pandas import Series, DataFrame # 환경설정 import numpy as np np.random.seed(12345) import matplotlib.pyplot as plt # DataFrame 객체 생성 # 같은 길이의 리스트에 담긴 사전을 이용하거나 NumPy 배열을 이용 data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002, 2003], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]} frame = pd.DataFrame(data) # 만들어진 DataFrame 의 색인은 Series 와 같은 방식으로 자동으로 대입되며 컬럼은 정렬되

Naver Blog

20220908 국비지원 리뷰!

첨부파일 0908_training.py 파일 다운로드 # 0908_training # 제 7장 연습문제 #1. 아이디 :첫자는 영문소문자, 단어길이 4자 이상 #2. 호스트이름 : 영문 소문자 시작, 단어길이 3자이상 #3. 최상위 도메인 : 영문소문자 3자리 이하 #4. 정규표현식 기본 패텅 : '메타문자@메타문자.메타문자 email = """[email protected] [email protected] [email protected] [email protected]""" from re import findall, match for e in email.split(sep='\n') : p = match(r'[a-z][a-zA-Z0-9]{3,}[@]\w{3,}[.]\w{0,3}',e) if p : print(e) #Q2 from re import findall emp = ["2014홍길동220","2002이순신","2010유관순260"] #함수정의 def name_pro(emp): text = find

Naver Blog

20220913 국비지원 리뷰!

# 0913-training # os.path 모듈관련 함수 import os.path import output as output os. getcwd() os.chdir('ch8_data') os.getcwd() os.path.abspath('lecture/step01_try_except.py') os.path.dirname('lecture/step01_try_except.py') os.path.exists('c:\\Users\\tj-bu\\PycharmProjects\\pythonProject') os.path.isfile('lecture/step01_try_except.py') os.path.isdir('lecture') os.path.split("c:\\test\\test1.txt") os.path.join('c\\test','test1.txt') os.path.getsize('lecture/txt.py') # 텍스트 자료수집 import os print(os.getcwd())

Naver Blog

20220905 국비지원 리뷰!

# 0905_training # 재귀함수 정의 : 1~n Counter = [] def Counter(n): if n == 0 : return 0 else : a = Counter(n-1) print(n,end=' ') print('n=',Counter(0)) print(Counter(5)) # 재귀함수 정의 : 1~n 누적합 def Adder(n): if n ==1 : return 1 else: result= n + Adder(n-1) print(n,end=' ') return result print('n=1 :',Adder(1)) print('\nn=5',Adder(5)) #=========================================================== # 문제 Q1 def StarCount(height) : if height == 1 : print(height*'*') return 1 else : result = height + StarCount(he

Naver Blog

20220906 국비지원 리뷰!

첨부파일 0906_training.py 파일 다운로드 # 0906_training # 생성자(현잔고, 입금액, 출금액) # method 1개 현잔고, 입금액, 출금액을 계산하여 업데이트된 잔고를 계산 # 현잔고 : 10,000원, 입금액 : 5,000원, 출금액 : 8,000원 # 업데이트된 잔고를 프린트 하세요. class account : def __init__(self, balance, inposit, whithdraw): self.balance = balance self.inposit = inposit self.whithdraw = whithdraw def display(self): display = self.balance + self. inposit - self.whithdraw return display bal = account(10000, 5000, 8000) new = bal.display() print(new) # 현재잔고와 sqrt값을 조회하는 클래스를 정의하세요

Naver Blog

20220907 국비지원 리뷰!

첨부파일 0907_training.py 파일 다운로드 # 0907_training # 복습 list = [1,2,3,4,5] *v1,v2=list print(v1, v2) print("실수 반환 ", format(3.1,"3.2f")) print("정수 소수점 반환", format(3345,",d")) name = '나나나' age = 32 ki = 13.222 print("이름 : %s, 나이 : %d, ki : %.2f"%(name,age,ki)) print("{0}, {2}, {1}".format(name,age,ki)) # 문자열 찾기 import re from re import findall st1 = '1234 abc홍길동 ABC_15523235_6 이다도시' print(findall('1234', st1)) print(findall('[0-9]',st1)) print(findall('[0-9]{3}',st1)) print(findall('[0-9]{3,}',st1)) p

Naver Blog

20220902 국비지원 리뷰!

# 0902_training. # abs(x) abs(10) abs(-10) abs(-123.45) # all(iterable) all([1,True, 10,-15.2]) all([1,True,0,-15.2]) all([1,False,0,-15.2]) #any(iterable) any(([1,False,0,15.2])) any([False,0,0]) #bin(number) bin(10) bin(15) #dir(x) x=[1,2,3,4,5] dir(x) x.append(6) print(x) #eval(expr) eval("2+10") eval(10 + "20*30") eval("20*30")+10 # hex(numbers) hex(10) hex(15) hex(64) #oct(number) oct(10) oct(7) oct(8) #ord(charactor) ord('0') ord('8') ord('a') #pow(x,y) pow('a',5) pow(10,3) pow(10,3) pow(1

1 2