python 3 中,a//b 表示的是 ⌊ab⌋ (向下取整)
def make_dir(_dir):
if os.path.exists(_dir):
return True
try:
os.makedirs(_dir)
return True
except:
return False
def make_thetas(xmin, xmax, n):
xs = np.linspace(xmin, xmax, n)
widths = (xs[1:]-xs[:-1])/2
thetas = xs[:-1]+widths
return theats
from matplotlib.pyplot as plt
def plot_decision_regions(X, y, classifier, resolution=0.02):
# X 中的每一行,也即每一个数据,仅限于二维(出于可视化的需要)
# classifier为已训练好的模型
# 直接进行对样本的predict
# 该函数仅涉及绘图,而不仅进行训练之类的操作
colors = ('lightgreen', 'cyan', 'gray', 'r', 'b')
markers = ('s', 'x', 'o', '^', 'v')
cmap = ListedColormap(colors[:np.unique(y)])
x1_min, x1_max = np.min(X[: 0])-1, np.max(X[:, 0])+1
x2_min, x2_max = np.min(X[: 1])-1, np.max(X[:, 1])+1
XX, YY = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([XX.ravel(), YY.ravel()]).T)
Z = Z.reshape(XX.shape)
plt.contourf(XX, YY, Z, alpha=.4, cmap=cmap)
plt.xlim((XX.min(), XX.max()))
plt.ylim((YY.min(), YY.max()))
# plot class samples
for idx, l in enumerate(np.unique(y)):
plt.scatter(X[y==l, 0], X[y==l, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=l)