path = 'https://raw.githubusercontent.com/DA4BAM/dataset/master/Carseats.csv'
carseat = pd.read_csv(path)
carseat.head()
target = 'Sales'
x = carseat.drop(target, axis=1)
y = carseat.loc[:, target]
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=.2, random_state = 20)
scaler = MinMaxScaler()
x_train = scaler.fit_transform(x_train)
x_val = scaler.transform(x_val)
1) 모델 선언
# feature 개수 저장
nfeatures = x_train.shape[1] #num of columns
nfeatures
# 메모리 정리(필수는 아님!)
clear_session()
# Sequential 타입 모델 선언
model = Sequential([Input(shape=(nfeatures,)),
Dense(1)])
# 모델요약
model.summary()
# 컴파일
model.compile(optimizer='adam',loss='mse')
2) 학습
model.fit(x_train,y_train)
3) 예측
pred = model.predict(x_val)
4) 검증
print(f'RMSE : {root_mean_squared_error(y_val, pred)}')
print(f'MAE : {mean_absolute_error(y_val, pred)}')
▪ 가중치 초기값을 할당한다. (초기 모델을 만든다.)
▪ (초기)모델로 예측한다.
▪ 오차를 계산한다. (loss function)
▪ 가중치 조절 : 오차를 줄이는 방향으로 가중치를 적절히 조절한다.(optimizer)
• 적절히 조절 → 얼마 만큼 조절할 지 결정하는 하이퍼파라미터 : learning rate (lr)
▪ 다시 처음으로 가서 반복한다.
• 전체 데이터를 적절히 나눠서(mini batch) 반복 : batch_size
• 전체 데이터를 몇 번 반복 학습할 지 결정 : epoch
선언된 모델에 대해 몇 가지 설정을 한 후 컴퓨터가 이해할 수 있는 형태로 변환하는 작업
가중치 한개의 업데이트 과정을 예로 들면
▪ 예를 들어, 내부요인은 70%, 외부요인은 30% 가중치를 준다면,
▪ 집값 = 0.7 내부요인 + 0.3 외부요인
▪ 기존 데이터를 받아들여, (우리는 정확히 알기 어렵지만) 뭔가 새로운 특징(New Feature)을 만들어 냄.
▪ 그 특징은 분명히 예측된 값과 실제 값 사이의 오차를 최소화 해주는 유익한 특징
▪ Hidden Layer에서는 기존 데이터가 새롭게 표현(Representation) 됨.
=> Feature Engineering이 진행된 것
로 변환 : sigmoid 함수
nfeatures = x_train.shape[1]
nfeatures
model2 = Sequential([Input(shape=(nfeatures,)),
Dense(1,activation='sigmoid')])
model2.summary()
model2.compile(optimizer=Adam(learning_rate=0.01), loss='binary_crossentropy')
result2 = model2.fit(x_train,y_train,
epochs=50,
validation_split=0.2).history
학습결과 그래프
예측 및 검증
pred2 = model2.predict(x_val)
pred2 = np.where(pred >= .5, 1, 0)
print(classification_report(y_val,pred2))
data['Species'] = data['Species'].map({'setosa':0, 'versicolor':1, 'virginica':2})
data.head()
nfeatures = x_train.shape[1] #num of columns
nfeatures
# 메모리 정리
clear_session()
# Sequential
model = Sequential( [Input(shape = (nfeatures,)),
Dense( 3, activation = 'softmax')] )
# 모델요약
model.summary()
model.compile(optimizer=Adam(learning_rate=0.1), loss= 'sparse_categorical_crossentropy')
history = model.fit(x_train, y_train, epochs = 50, validation_split=0.2).history
pred = model.predict(x_val)
pred[:5]
# 전체에 적용해서 변환합시다. ( 가장 큰 확률의 인덱스로 변환)
pred_1 = pred.argmax(axis=1)
pred_1
print(confusion_matrix(y_val, pred_1))
print(classification_report(y_val, pred_1))