중심극한정리
표준정규분포
1표준편차 안에는 68%
2표준편차 안에는 95%
3표준편차 안에는 99.7%
파이썬300제, 점프 투 파이썬 연습문제 시험 20-25문제, 2시간, 다음주 월요일
최대우도함수 , 주성분분석 설명 ??
분류기
이진분류 - 로지스틱회귀
경계면 기준 나누기 - svm
knn
뭘해야할지모를때 ? ? cross validation하기
Cross vaildation
knn 3차원 예제
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 3)
training_points = [
[0.5, 0.2, 0.1],
[0.9, 0.7, 0.3],
[0.4, 0.5, 0.7]
]
training_labels = [0, 1, 1]
classifier.fit(training_points, training_labels)
unknown_points = [
[0.2, 0.1, 0.7],
[0.4, 0.7, 0.6],
[0.5, 0.8, 0.1]
]
guesses = classifier.predict(unknown_points)
guesses
dataset_loading_서브노트.txt
0.01MB
scikit-learn_서브노트.txt
0.02MB
scikit-learn에서 제공하는 데이터 예제
=======================================
scikit-learn에서 제공하는 데이터
=======================================
#
# 보스턴 주택 가격 데이터 (회귀 분석용)
#
# load_boston() 명령으로 로드하고 DESCR 속성으로 문서 설명을 볼 수 있음
from sklearn.datasets import load_boston
boston = load_boston()
type(boston)
boston
print(boston.data.shape)
print(boston.data)
print(boston.target.shape)
print(boston.target)
print(boston.feature_names)
print(boston.DESCR)
print(boston.filename)
# 데이터는 후속 작업을 위해 Pandas 데이터프레임 형태로 변환
dfX = pd.DataFrame(boston.data, columns=boston.feature_names)
dfy = pd.DataFrame(boston.target, columns=["MEDV"])
df = pd.concat([dfX, dfy], axis=1)
df.tail()
# seaborn의 pairplot 명령으로 각 데이터의 분포와 데이터들간의 상관관계 파악
import seaborn as sns
cols = ["MEDV", "RM", "AGE", "RAD"]
sns.pairplot(df[cols])
plt.show()
#
# 당뇨병 데이터 (회귀 분석용)
#
from sklearn.datasets import load_diabetes
diabetes = load_diabetes()
print(diabetes.DESCR)
df = pd.DataFrame(diabetes.data, columns=diabetes.feature_names)
df["Target"] = diabetes.target
df.tail()
import seaborn as sns
cols = ["Target", "bmi", "s1", "s6"]
sns.pairplot(df[cols])
plt.show()
#
# 붓꽃 데이터 (분류 분석용)
#
from sklearn.datasets import load_iris
iris = load_iris()
print(iris.DESCR) # load_iris() 명령으로 로드한 데이터의 DESCR 속성 확인
# Pandas패키지로 데이터프레임을 만들어 일부 데이터를 살펴본다.
df = pd.DataFrame(iris.data, columns=iris.feature_names)
sy = pd.Series(iris.target, dtype="category")
sy = sy.cat.rename_categories(iris.target_names)
df['species'] = sy
df.tail()
# 각 특징값의 분포와 상관관계를 히스토그램과 스캐터플롯으로 나타내면 다음과 같다.
sns.pairplot(df, hue="species")
plt.show()
# 이 분포를 잘 살펴보면 꽃잎의 길이만으로도 세토사와 다른 종을 분류할 수 있다는 것을 알 수 있다.
sns.distplot(df[df.species != "setosa"]["petal length (cm)"], hist=True, rug=True, label="setosa")
sns.distplot(df[df.species == "setosa"]["petal length (cm)"], hist=True, rug=True, label="others")
plt.legend()
plt.show()
# 하지만 베르시칼라와 버지니카는 이 방법으로 완벽한 구분이 불가능하다.
sns.distplot(df[df.species == "virginica"]["petal length (cm)"], hist=True, rug=True, label="virginica")
sns.distplot(df[df.species == "versicolor"]["petal length (cm)"], hist=True, rug=True, label="versicolor")
plt.legend()
plt.show()
#
# 와인 데이터 (분류 분석용)
#
from sklearn.datasets import load_wine
wine = load_wine()
wine
print(wine.target)
print(wine.target_names)
print(wine.DESCR)
df = pd.DataFrame(wine.data, columns=wine.feature_names)
df.tail()
sy = pd.Series(wine.target, dtype="category")
sy
help(sy.cat.rename_categories)
sy = sy.cat.rename_categories(wine.target_names)
sy
df['class'] = sy
df.tail()
# 일부 특징값의 분포와 상관관계를 히스토그램과 스캐터플롯으로 나타내면 다음과 같다.
sns.pairplot(vars=["alcohol", "alcalinity_of_ash", "total_phenols", "flavanoids"],
hue="class", data=df)
plt.show()
#
# 유방암 진단 데이터 (분류 분석용)
#
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
print(cancer.DESCR)
df = pd.DataFrame(cancer.data, columns=cancer.feature_names)
sy = pd.Series(cancer.target, dtype="category")
sy = sy.cat.rename_categories(cancer.target_names)
df['class'] = sy
df.tail()
sns.pairplot(vars=["worst radius", "worst texture", "worst perimeter", "worst area"],
hue="class", data=df)
plt.show()
# 유방암 데이터 분석 예제 : https://jfun.tistory.com/108
# 유방암 데이터 분석 by SVM : https://jfun.tistory.com/115
#
# 대표 수종 데이터(분류 분석용)
#
from sklearn.datasets import fetch_covtype
covtype = fetch_covtype()
print(covtype.DESCR)
df = pd.DataFrame(covtype.data,
columns=["x{:02d}".format(i + 1) for i in range(covtype.data.shape[1])],
dtype=int)
sy = pd.Series(covtype.target, dtype="category")
df['covtype'] = sy
df.tail()
pd.DataFrame(df.nunique()).T
df.iloc[:, 10:54] = df.iloc[:, 10:54].astype('category')
df_count = df.pivot_table(index="covtype", columns="x14", aggfunc="size")
sns.heatmap(df_count, cmap=sns.light_palette("gray", as_cmap=True), annot=True, fmt="0")
plt.show()
#
# 뉴스 그룹 텍스트 데이터 (분류 분석용)
#
#
# 로이터 말뭉치 (분류 분석용)
#
#
# 숫자 필기 이미지 데이터 (분류 분석용)
#
#
# 올리베티 얼굴 사진 데이터 (분류 분석용)
#
#
# Labeled Faces in the Wild (LFW) 데이터 (분류 분석용)
#
가상데이터 예제
#
# 가상 데이터 (회귀 분석용)
#
# 때로 회귀분석 결과를 검증하기 위해 make_regression() 함수로 가상의 데이터를 생성함
# 가상 데이터 첫번째 예제:
# 독립 변수가 1개이고 noise 인수값이 10인 경우의 가상데이터
from sklearn.datasets import make_regression
X, y, w = make_regression(
n_samples=50, n_features=1, bias=100, noise=10, coef=True, random_state=0
)
print("w:\n", w)
import numpy as np
xx = np.linspace(-3, 3, 100)
xx
y0 = w * xx + 100
def visualization():
import matplotlib.pyplot as plt
plt.plot(xx, y0, "r-")
plt.scatter(X, y, s=100)
plt.xlabel("x")
plt.ylabel("y")
plt.title("make_regression Example (noise=10 case)")
plt.show()
visualization()
# 가상 데이터 두번째 예제:
# 독립 변수가 2개인 표본 데이터를 생성하여 스캐터 플롯 생성
# 종속 변수 값은 점의 명암으로 표시
X, y, w = make_regression(
n_samples=300, n_features=2, noise=10, coef=True, random_state=0
)
def visualization():
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=y, s=100, cmap=mpl.cm.bone)
plt.xlabel("x1")
plt.ylabel("x2")
plt.axis("equal")
# 두 독립 변수가 서로 독립이고 둘 다 종속 변수와 상관 관계가 있는 경우
plt.title("two independent variables are independent of each other and both correlate with dependent variables")
plt.show()
visualization()
# 가상 데이터 세번째 예제:
# 독립 변수 중 실제로 종속 변수에 영향을 미치는 독립 변수는 하나 뿐이라면 n_informative=1로 설정
# 종속 변수 값은 점의 명암으로 표시
X, y, w = make_regression(
n_samples=300, n_features=2, n_informative=1, noise=10, coef=True, random_state=0
)
def visualization():
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=y, s=100, cmap=mpl.cm.bone)
plt.xlabel("x1")
plt.ylabel("x2")
plt.axis("equal")
# 두 독립 변수가 서로 독립이고 둘 중 하나만 종속 변수와 상관 관계가 있는 경우
plt.title("Two independent variables are independent of each other and only one of them correlates with dependent variables.")
plt.show()
visualization()
# 가상 데이터 네번째 예제:
# 두 독립 변수가 서로 독립이 아니고 상관관계를 가지는 경우에는 tail_strength 인수를 0에 가까운 작은 값으로 설정
X, y, w = make_regression(
n_samples=300, n_features=2, effective_rank=1, noise=10, coef=True, random_state=0, tail_strength=0
)
def visualization():
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=y, s=100, cmap=mpl.cm.bone)
plt.xlabel("x1")
plt.ylabel("x2")
plt.axis("equal")
# 두 독립 변수가 독립이 아닌 경우
plt.title("two independent variables are not independent")
plt.show()
visualization()
'인공지능 > 머신러닝' 카테고리의 다른 글
sklearn.model (0) | 2021.07.08 |
---|---|
Scikit-Learn (0) | 2021.07.08 |
Sclkit - Learn을 이용 군집 (0) | 2021.07.07 |
툴 사용법 ( 이클립스, 주피터, 코랩, 아톰 ) (0) | 2021.07.06 |
Sclkit - Learn을 이용 분류 (0) | 2021.07.05 |