데이터 처리

# 1. Pandas 가져오기
import pandas as pd
# 2. 데이터 불러오기
data = pd.read_csv('diabetes_data.csv')
data.head()

# 데이터 통계치 확인하기

data.describe()

# 3. X/y 나누기
X = data.iloc[:,:-1].values
y = data.iloc[:,-1].values

# values를 붙여서 numpy array형태로 가져온다!!!!! 매우 중요하다!!!! 큰 깨달음
print(X.shape)
print(y.shape)
# 4. Train set, Test set 나누기
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.25, random_state=42)


X_val, X_test, y_val, y_test = train_test_split(X_test,y_test, 
                                                test_size=0.5,
                                                random_state=19)
print(X_train.shape)
print(X_val.shape)
print(X_test.shape)
print(y_train.shape)
print(y_val.shape)
print(y_test.shape)

Keras 모델 만들기

# 5. Keras 패키지 가져오기

from keras.models import Sequential
from keras.layers import Dense

# 6. MLP 모델 생성

model = Sequential()

model.add(Dense(units=64, input_dim=8, activation='relu'))
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))

model.summary()

# 7. Compile - Optimizer, Loss function 설정
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# 8. 학습시키기
from keras.callbacks import EarlyStopping, ModelCheckpoint

early_stop = EarlyStopping(patience=20)
batch_size = 32
epochs = 200
history = model.fit(X_train,y_train,
                  batch_size=batch_size,
                  nb_epoch=epochs,
                  validation_data=(X_val,y_val),
                  callbacks=[early_stop],
                  verbose=1
                  )

# 9. 모델 평가하기
train_acc = model.evaluate(X_train,y_train)
test_acc = model.evaluate(X_test,y_test)

print(train_acc)
print(test_acc)

시각화

# 10. 학습 시각화하기
import matplotlib.pyplot as plt

plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])

plt.title('Accuracy')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend(['train','val'], loc = 'upper left')
plt.show()

# loss 값 그래프 그리기
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])

plt.title('loss')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(['train','val'], loc = 'upper left')
plt.show()

# 11. 모델 저장
model_path ='diabet_model.h5'
model.save(model_path)
# 12. 모델 불러오기

from keras.models import load_model

loaded_model = load_model(model_path)
print(loaded_model.summary())

 

'Data Anaylsis > Deep Learning' 카테고리의 다른 글

딥러닝 3일차  (0) 2020.03.18
딥러닝 2일차  (0) 2020.03.17
AND,OR/XOR 문제 keras로 구현!  (0) 2020.03.16
Deep learning 1일차  (0) 2020.03.16
conda 가상환경 설치  (1) 2020.03.13

내가 입력하는 점수를 학점으로 변환시키는 코드

jumsu = int(input('점수를 입력하세요 : '))
if jumsu >=95:
    res='A+'
elif jumsu >=90:
    res = 'A'
elif jumsu >=85:
    res = 'B+'
elif jumsu >=80:
    res = 'B'
elif jumsu >=75:
    res = 'C+'
elif jumsu >=60:
    res = 'C'
elif jumsu >=55:
    res = 'D+'
elif jumsu >=50:
    res = 'D'
else:
    res = 'F'
print(res,'\n학점입니다. ^^')

 

사용자가 입력하는 값(숫자)를 구구단 형식으로 출력

num = int(input('Input number.\n'))
i=0
print('************{}dan************'.format(num))
while i<9:
    i += 1
    print('{}X{}={}'.format(num, i, num*i)) 
print('*****************************')

 

99를 입력할 때 까지 숫자를 무한으로 입력받아서 계속 구구단 출력

while True:
    num = int(input('Input number.\n'))
    if num<=0:
        continue
    elif num == 99:
        break
    print('************{}dan************'.format(num))
    for i in range(1,10):
        print('{}X{}={}'.format(num, i, num*i))
    print('*****************************')

 

 

윤년 계산기 

4로 나누어지면 윤년, 100으로 나누어지면 윤년 X, 400으로 나누어지면 윤년

while True:
    year = int(input('연도를 입력하세요 : '))
    if (year % 4 == 0) :
        if (year % 400 ==0):
            print('{}년은 윤년입니다.'.format(year))
            
        elif (year % 100 == 0):
            print('{}년은 윤년이 아닙니다.'.format(year))
        else: 
            print('{}년은 윤년입니다.'.format(year))
    else :
        print('{}년은 윤년이 아닙니다.'.format(year))
    if year == -1:
        break
while True:
    year = int(input('연도를 입력하세요 : '))
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print('{}년은 윤년입니다.'.format(year))
    else :
        print('{}년은 윤년이 아닙니다.'.format(year))
    if year == -1:
        break

 

for 문

for문 (반복문)은 while문과는 살짝 다르다.

while문은 무한루프가 가능하지만, for문은 그렇지않다.

for문은 대게 루프를 몇 번 돌지를 "알"고있을때 사용한다.

 

따라서 while, for문중 상황에 맞게 골라서 사용할 줄 알아야한다.

start_num = int(input('시작값을 입력하세요 :'))
end_num = int(input('끝값을 입력하세요: '))
step_num = int(input('증가값을 입력하세요.'))
total = 0
for i in range(start_num, end_num, step_num):
    total = total + i
print('{}에서 {}까지 {}씩 증가시킨 값의 합계 : '.format(start_num, end_num, step_num))
num = int(input('값을 입력하세요 :'))
sum_of_num = 0
for i in range(1,num+1):
    sum_of_num = sum_of_num + i
    
print('1에서 {}까지의 합계 : {} '.format(num,sum_of_num))
for i in range(1,9,1):
    print('#  {}단  #'.format(i+1),end=' ')
print()
for i in range(1,10,1):
    for j in range(2,10,1):
        print('%1dX %1d=%4d'%(j,i,i*j), end = " ")
    print()
    
        
    
    

'Data Anaylsis > python basic' 카테고리의 다른 글

클래스  (0) 2020.01.06
파이썬기초(5)  (0) 2019.12.31
파이썬기초(4)  (0) 2019.12.30
파이썬기초(2)  (0) 2019.12.26
파이썬 기초(1)  (1) 2019.12.26

 

%로 문자열을 formatting 할 수 있다.

print('%5s'%('*'*1))
print('%5s'%('*'*2))
print('%5s'%('*'*3))
print('%5s'%('*'*4))
print('%5s'%('*'*5))

 

별찍기

n = int(input('Input a number '))
print('%-5s'%('*'*1)*n)
print('%-5s'%('*'*2)*n)
print('%-5s'%('*'*3)*n)
print('%-5s'%('*'*4)*n)
print('%-5s'%('*'*5)*n)



n = int(input('시작! '))
while n>2: 
    for i in range(1,6):
        print(('*'*i+' '*(6-i))*n)
    n-=1

 

 

 

n = int(input('Input a number '))
Pi = 3.14
print('Circumference = %2.1f'%(2*n*Pi))
print('Area          = %2.1f'%(n**2*Pi))

 

 

입력받은 금액을 각 지폐 몇장으로 나눠지는지 알려주는 것

n = int(input('지폐로 교환할 돈은 얼마? '))
a_50000 = n//50000
b = n-a_50000*50000 # b %= 50000
a_10000 = b//10000
b -= a_10000*10000
a_5000 = b//5000
b -= a_5000*5000
a_1000 = b//1000
b -= a_1000*1000
a_0 = b%1000 

print('50000원짜리 ==> {}'.format(a_50000))
print('10000원짜리 ==> {}'.format(a_10000))
print('5000원짜리 ==> {}'.format(a_5000))
print('1000원짜리 ==> {} '.format(a_1000))
print('지폐로 바꾸지 못한 돈 ==> {} '.format(a_0))

 

 

weight = float(input('몸무게를 kg 단위로 입력: '))
height = float(input('키를 미터 단위로 입력: '))
BMI = (weight)/(height**2)
print('당신의 BMI= {}'.format(BMI))

 

input_money = int(input('투입한 돈: '))
cost_of_stuff = int(input('물건값: '))
change = input_money-cost_of_stuff
change_of_500 = change//500
change_of_100 = (change - change_of_500*500)//100

print('거스름돈: {}'.format(change))
print('500원 동전의 개수: {}'.format(change_of_500))
print('100원 동전의 개수: {}'.format(change_of_100))

 

'Data Anaylsis > python basic' 카테고리의 다른 글

클래스  (0) 2020.01.06
파이썬기초(5)  (0) 2019.12.31
파이썬기초(4)  (0) 2019.12.30
파이썬기초(3)  (0) 2019.12.26
파이썬 기초(1)  (1) 2019.12.26

+ Recent posts