
인공지능이란?
AI를 배워야할 이유
AI의 응용 분야
AI 관련 세부 분야
튜링 테스트를 이용한 지능의 정의
기계가 사람처럼 생각하게 만들기
이성적인 에이전트
범용 문제 해결기
__GPS를 이용한 문제 해결 방법
지능적인 에이전트 구현 방법
__모델의 종류
+파이썬 3 설치
__우분투에 설치하기
__맥 OS X에 설치하기
__윈도우에 설치하기
패키지 설치
데이터 불러오기
요약
지도 학습 및 비지도 학습
+분류
데이터 전처리
__이진화
__평균 제거
__크기 조정(scaling)
__정규화
레이블 인코딩
로지스틱 회귀 분류기
나이브 베이즈 분류기
오차 행렬
+서포트 벡터 머신
SVM으로 소득 계층 분류하기
회귀 분석
단순 회귀 분석 모델 만들기
다중 회귀 분석 모델 만들기
서포트 벡터 회귀 모델로 주택 가격 예측하기
요약
인공지능(Artificial Intelligence, AI)은 컴퓨터 시스템이 인간의 학습, 추론, 결정 등 인간과 유사한 지능적 작업을 수행하는 능력을 의미한다.
튜링 테스트는 컴퓨터가 인간과 대화를 나누었을 때 인간과의 구별이 어렵다면 그 컴퓨터를 지능이 있다고 간주하는 것을 말한다.
GPS(Global Positioning System)를 이용하여 위치 정보를 획득하고 경로를 계획하는 문제 해결 방법이다.
연속형 변수를 이진형으로 변환하는 과정으로, 특정 임계값을 기준으로 변수를 0 또는 1로 변환한다.
데이터에서 평균을 빼주는 과정으로, 데이터를 중심으로 재조정한다.
데이터의 값 범위를 일정한 범위로 조정하는 과정으로, 주로 Min-Max 스케일링 또는 표준화(z-score normalization)를 사용한다.
데이터의 크기를 단위 벡터로 만드는 과정으로, 각 데이터 포인트의 크기를 1로 만든다.
범주형 데이터를 수치형으로 변환하는 과정으로, 각 범주에 고유한 숫자를 할당한다.
이진 분류 작업에 널리 사용되는 회귀 기반의 분류 알고리즘이다.
통계적 분류 기법 중 하나로, 베이즈 정리를 기반으로 하는 간단한 확률적 분류 알고리즘이다.
데이터를 고차원 공간으로 매핑하여 최적의 경계를 찾는 분류 알고리즘이다.
회귀 분석은 입력 데이터와 연속형 출력 변수 간의 관계를 모델링하는 작업이다.
하나의 입력 변수와 출력 변수 간의 선형 관계를 모델링하는 회귀 분석 모델이다.
여러 개의 입력 변수와 출력 변수 간의 선형 관계를 모델링하는 회귀 분석 모델이다.
SVM을 회귀 분석에 적용한 모델로, 비선형 회귀 문제에도 효과적으로 적용될 수 있다.
분류 모델의 성능을 평가하기 위해 사용되는 행렬로, 실제 클래스와 예측 클래스 간의 관계를 보여준다.
이 메시지는 scikit-learn에서 Boston 주택 가격 데이터셋을 불러오려고 할 때 발생한 오류 메시지입니다. 오류 메시지에 따르면 load_boston 함수는 scikit-learn 버전 1.2부터 제거되었습니다. 또한, 이 데이터셋에는 윤리적인 문제가 있어서 사용을 권장하지 않는다고 합니다. 해당 데이터셋에는 인종적 자기분리가 주택 가격에 긍정적인 영향을 미친다는 가정을 내포하는 비가역적인 변수 "B"가 포함되어 있습니다. 또한 이 데이터셋을 만드는 데 있어서의 연구 목적이 대기 질의 영향을 연구하는 것이었지만, 이 가정의 타당성을 충분히 입증하지 못했습니다.
따라서 scikit-learn 개발자는 데이터셋을 사용하는 것을 강력히 권장하지 않습니다. 대신에 이 데이터셋 대신에 California 주택 데이터셋이나 Ames 주택 데이터셋을 사용할 것을 권장합니다.
해당 오류 메시지를 보면, 올바른 대체 데이터셋을 사용하는 방법에 대한 정보가 제공되어 있습니다. 번거로우시겠지만, 이 메시지에 나와 있는 대안 데이터셋을 사용하는 것이 좋을 것입니다.
(base) eunseo-ko@cannes7ui-MacBookPro ~ main ±✚ python3
Python 3.11.7 (main, Dec 15 2023, 12:09:56) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sklearn import datasets
>>> house_prices = datasets.load_boston()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/anaconda3/lib/python3.11/site-packages/sklearn/datasets/__init__.py", line 156, in __getattr__
raise ImportError(msg)
ImportError:
`load_boston` has been removed from scikit-learn since version 1.2.
The Boston housing prices dataset has an ethical problem: as
investigated in [1], the authors of this dataset engineered a
non-invertible variable "B" assuming that racial self-segregation had a
positive impact on house prices [2]. Furthermore the goal of the
research that led to the creation of this dataset was to study the
impact of air quality but it did not give adequate demonstration of the
validity of this assumption.
The scikit-learn maintainers therefore strongly discourage the use of
this dataset unless the purpose of the code is to study and educate
about ethical issues in data science and machine learning.
In this special case, you can fetch the dataset from the original
source::
import pandas as pd
import numpy as np
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
Alternative datasets include the California housing dataset and the
Ames housing dataset. You can load the datasets as follows::
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()
for the California housing dataset and::
from sklearn.datasets import fetch_openml
housing = fetch_openml(name="house_prices", as_frame=True)
for the Ames housing dataset.
[1] M Carlisle.
"Racist data destruction?"
<https://medium.com/@docintangible/racist-data-destruction-113e3eff54a8>
[2] Harrison Jr, David, and Daniel L. Rubinfeld.
"Hedonic housing prices and the demand for clean air."
Journal of environmental economics and management 5.1 (1978): 81-102.
<https://www.researchgate.net/publication/4974606_Hedonic_housing_prices_and_the_demand_for_clean_air>
>>> print(house_prices.data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'house_prices' is not defined
>>> from sklearn.datasets import fetch_califormia_housing
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'fetch_califormia_housing' from 'sklearn.datasets' (/opt/anaconda3/lib/python3.11/site-packages/sklearn/datasets/__init__.py)
>>> from sklearn.datasets import fetch_california_housing
>>> housing = fetch_california_housing()
>>> print(housing.data)
[[ 8.3252 41. 6.98412698 ... 2.55555556
37.88 -122.23 ]
[ 8.3014 21. 6.23813708 ... 2.10984183
37.86 -122.22 ]
[ 7.2574 52. 8.28813559 ... 2.80225989
37.85 -122.24 ]
...
[ 1.7 17. 5.20554273 ... 2.3256351
39.43 -121.22 ]
[ 1.8672 18. 5.32951289 ... 2.12320917
39.43 -121.32 ]
[ 2.3886 16. 5.25471698 ... 2.61698113
39.37 -121.24 ]]
>>> print(housing.target)
[4.526 3.585 3.521 ... 0.923 0.847 0.894]
>>>
분류 (classification):
- 데이터를 지정한 수만큼의 클래스 (범주)로 나누는 기법
머신 러닝에서의 분류:
- 머신 러닝에서는 주어진 데이터 항목이 속하는 클래스를 결정하는 문제를 다룰 때 분류 기법을 활용함
데이터 전처리 (preprocessing): 미가공 (raw) 데이터로 머신 러닝 알고리즘을 학습시키기 전에 데이터의 포맷을 머신 러닝 알고리즘이 처리할 수 있는 형태로 변환하는 작업
전처리 기법:
- 이진화
이진화 (binarization): 숫자를 불리언 (boolean) 수 (이진수)로 변환하는 기법
data_binarized = preprocessing.Binarizer(threshold=2.1).transform(input_data)
# 결과를 보면 2.1보다 큰 값은 1로, 나머지는 0으로 변환됨
data_scaled = preprocessing.scale(input_data)
# 결과를 보면 평균값은 0에, 표준편차는 1에 가깝게 조정됨
data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1))
data_scaler_minmax = data_scaler_minmax.fit_transform(input_data)
# 결과를 보면 각 행마다 최댓값은 1로, 나머지는 1을 기준으로 상대적인 값으로 표현됨
data_normalized_11 = preprocessing.mormalize(input_data, norm='11') # L1
data_normalized_12 = preprocessing.mormalize(input_data, norm='12') # L2
# 패키지 임포트
import numpy as np
from sklearn import preprocessing
# 샘플 입력 레이블 정의
input_label = ['red', 'black', 'red', 'green', 'black', 'yellow', 'white']
# 레이블 인코더 오브젝트 생성 후 레이블로 학습 시킴
encoder = preprocessing.LabelEncoder()
encoder.fit(input_labels)
# 단어와 숫자 사이의 매핑 관계를 화면 출력
for i, item in enumerate(encoder.classes_):
print(item, '-->', i)
# 샘플에 있는 레이블 중에서 몇 개를 골라 인코딩 (레이블 인코딩)
test_labels = ['green', 'red', 'black']
encoded_values = encoder.transform(test_labels)
print( test_labels )
print( list(encoded_values) )
# 반대로 숫자를 레이블 문자로 디코딩 (숫자 값 디코딩)
encoded_values = [3, 0, 4, 1]
decoded_list = encoder.inverse_transform(encoded_values)
print( encoded_values )
print( list(decoded_list) )
로지스틱 회귀 분석 (logistic regression):
- 입력 변수와 출력 변수의 관계를 표현하는 기법 중 하나
- 입력 = 독립 변수
- 출력 = 종속 변수; 종속 변수의 수는 고정됨
- 분류 문제를 다룰 때는 종속 변수로 분류할 클래스 (그룹)를 표현함 (?) p.60
로지스틱 함수:
- 독립 변수와 종속 변수의 관계를 로지스틱 함수를 통해 계산된 확률로 표현함
- 시그모이드 곡선으로 표현함
- 시그모이드 곡선 (sigmoid curve): S자를 눕힌 모양의 곡선으로, 여러 가지 매개변수로 구성된 함수를 만들 때 주로 사용
- 일반 선형 모델과 밀접한 관련이 있음
- 일반 선형 모델 (generalized linear model; 선형 회귀 분석): 데이터의 분포를 표현하는 직선 중 오차가 가장 적은 직선을 구하는 모델
로지스틱 회귀 분석을 이용한 분류기 만들기
- Tkinter 패키지 이용
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
from utilities import visualize_classifier
# 샘플 입력 데이터를 2차원 벡터로 정의하고, 이에 대한 레이블도 정의함
X = np.array([[3.1,7.2],[4,6.7],[2.9,8],[5.1,4.5],[6,5],[5.6,5],[3.3,0.4],[3.9,0.9],[2.8,1],[0.5,3.4],[1,4],[0.6,4.9]])
y = np.array([0,0,0,1,1,1,2,2,2,3,3,3])
#로지스틱 회귀 분류기 오브젝트 생성
classifier = linear_model.LogisticRegression(solver='liblinear', C=1)
# 분류기 학습
classifier.fit(X,y)
# 분류된 클래스들의 경계 값 이용해 분류기의 성능을 시각적으로 표현
visualize_classifier(classifier,X,y)
import numpy as np
import matplotlib.pyplot as plt
def visualize_classifier(classifier, X, y):
# 메시 그리드에서 사용할 X와 Y에 대한 최댓값과 최솟값 정의
# 메시 그리드 (mesh grid): 함수를 평가하는 데 사용할 값들의 집합; 각각의 클래스의 경계 값을 시각적으로 표현하는 데 활용함
min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0
# min, max 값 이용하여 메시 그리드를 그릴 때 적용할 간격 정의
mesh_step_size = 0.01
# 메시 그리드의 X 값과 Y 값 정의
x_vals, y_vals = np.meshgrid(np.arrange(min_x, max_x, mesh_step_size),
np.arrange(min_y, max_y, mesh_step_size))
output = classifier.predict(np.c_[x_vals.ravel(), y_vals.ravel()])
output = output.reshape(x_vals.shape)
plt.figure()
plt.pcolormesh(x_vals, y_vals, output, cmap=plt.cm.gray)
plt.scatter(X[:,0], X[:,1], c=y, s=75, edgecolors='black', linewidths=1, cmap=plt.cm.Paired)
plt.xlim(x_vals.min(), x_vals.max())
plt.ylim(y_vals.min(), y_vals.max())
plt.xticks((np.arange(int(X[:,0].min()-1), int(X[:,0].max()+1), 1.0)))
plt.yticks((np.arange(int(X[:,1].min()-1), int(X[:,1].max()+1), 1.0)))
plt.show()