클라우드 분류
[KT클라우드]AI Studio 소스코드 가이드 - 샘플코드
작성자 정보
- 관리자 작성
- 작성일
컨텐츠 정보
- 5,302 조회
- 0 추천
- 목록
본문
AI Studio 모델 학습 코드 작성을 위한 샘플코드입니다.
모델 학습
Keras 프레임워크
from __future__ import print_functionimport numpy as npimport pandas as pdfrom tensorflow.python import kerasfrom tensorflow.python.keras import backend as Kfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Dense, Dropout, Flattenfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2Dfrom sklearn.datasets import load_irisfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split"""AI Studio와 연계를 위한 기본 객체 생성"""from aicentro.session import Sessionaistudio_session = Session(verify=False)"""학습 모델 개발 시 프레임워크별 객체 사용"""from aicentro.framework.keras import Keras as AistudioFrmaistudio_framework = AistudioFrm(session=aistudio_session)"""모델 코드 작성"""batch_size = 128num_classes = 3epochs = 10 data = load_iris() X = data.datay = data.target encoder = LabelEncoder()y1 = encoder.fit_transform(y)Y = pd.get_dummies(y1).values X_train, X_test, y_train, y_test = train_test_split(X, Y,test_size=0.2, random_state=1) model = Sequential()model.add(Dense(64,input_shape=(4,),activation='relu'))model.add(Dense(64,activation='relu'))model.add(Dense(3,activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='Adam',metrics=['accuracy'])model.summary() """모델 학습 시 Accuracy 와 Loss 값을 AI Studio로 전송하여 UI 상에 노출제공된 Metric Callback 사용"""history = aistudio_framework.get_metric_callback()model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(X_test, y_test), callbacks=[history]) y_test_pred = model.predict(X_test, batch_size=128, verbose=1)y_label = data.target_names.tolist()y_test_c = np.argmax(y_test, axis=1).reshape(-1, 1)y_test_pred_c = np.argmax(y_test_pred, axis=1).reshape(-1, 1)"""모델 학습 후 결과를 저장하고 해당 결과를 UI 상에 노출"""aistudio_framework.plot_confusion_matrix(y_test_c, y_test_pred_c, target_names=y_label, title='Confusion Matrix')aistudio_framework.classification_report(y_test_c, y_test_pred_c, target_names=y_label)aistudio_framework.plot_roc_curve(y_test, y_test_pred, len(y_label), y_label)'''학습된 모델 저장'''aistudio_framework.save_model(model, model_name='iris-classification') Scikit Learn 프레임워크
from __future__ import print_functionimport numpy as np import pandas as pd """AI 포탈과 연계를 위한 기본 객체 생성 """from aicentro.session import Session session = Session(verify=False) """학습 모델 개발 시 프레임워크별 객체 사용 """from aicentro.framework.framework import BaseFramework as Frm framework = Frm(session=session) """모델 코드 작성 """from sklearn.linear_model import LogisticRegression from sklearn import datasets from sklearn.datasets import load_iris from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split data = load_iris() X = data.data y = data.target y_label = data.target_names.tolist() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) logreg = LogisticRegression(C=1e5) logreg.fit(X_train, y_train) y_test_pred = logreg.predict(X_test) y_test_c = y_test.reshape(-1, 1) y_test_pred_c = y_test_pred.reshape(-1, 1) "무단배포금지: 클라우드포털(www.linux.co.kr)의 모든 강좌는 저작권에 의해 보호되는 콘텐츠입니다. 무단으로 복제하여 배포하는 행위는 금지되어 있습니다."
관련자료
-
링크
-
이전
-
다음
댓글 0
등록된 댓글이 없습니다.
