tensor flow 의 과 의합 문제 실전 을 상세히 해석 하 다.
11505 단어 tensorflow과 의합
1.데이터 세트 구축
우리 가 사용 하 는 데이터 세트 견본 의 특성 벡터 길 이 는 2 이 고 라벨 은 0 또는 1 로 각각 2 가지 유형 을 대표 합 니 다.scikit-learn 라 이브 러 리 에서 제공 하 는 Makemoons 도 구 는 임의의 다 중 데이터 훈련 집 을 만 들 수 있 습 니 다.
import matplotlib.pyplot as plt
#
import numpy as np
import seaborn as sns
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, Sequential, regularizers
from mpl_toolkits.mplot3d import Axes3D
의합 현상 을 보 여주 기 위해 우 리 는 1000 개의 견본 데이터 만 샘플링 하고 표준 차 가 0.25 인 고 스 소음 데 이 터 를 추가 했다.
def load_dataset():
#
N_SAMPLES = 1000
#
TEST_SIZE = None
# moon 1000 , -
X, y = make_moons(n_samples=N_SAMPLES, noise=0.25, random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=42)
return X, y, X_train, X_test, y_train, y_test
make_plot 함 수 는 견본 의 좌표 X 와 견본 의 라벨 y 에 따라 데이터 분포 도 를 편리 하 게 그 릴 수 있 습 니 다.
def make_plot(X, y, plot_name, file_name, XX=None, YY=None, preds=None, dark=False, output_dir=OUTPUT_DIR):
# , X 2D , y
if dark:
plt.style.use('dark_background')
else:
sns.set_style("whitegrid")
axes = plt.gca()
axes.set_xlim([-2, 3])
axes.set_ylim([-1.5, 2])
axes.set(xlabel="$x_1$", ylabel="$x_2$")
plt.title(plot_name, fontsize=20, fontproperties='SimHei')
plt.subplots_adjust(left=0.20)
plt.subplots_adjust(right=0.80)
if XX is not None and YY is not None and preds is not None:
plt.contourf(XX, YY, preds.reshape(XX.shape), 25, alpha=0.08, cmap=plt.cm.Spectral)
plt.contour(XX, YY, preds.reshape(XX.shape), levels=[.5], cmap="Greys", vmin=0, vmax=.6)
# , m=markers
markers = ['o' if i == 1 else 's' for i in y.ravel()]
mscatter(X[:, 0], X[:, 1], c=y.ravel(), s=20, cmap=plt.cm.Spectral, edgecolors='none', m=markers, ax=axes)
#
plt.savefig(output_dir + '/' + file_name)
plt.close()
def mscatter(x, y, ax=None, m=None, **kw):
import matplotlib.markers as mmarkers
if not ax: ax = plt.gca()
sc = ax.scatter(x, y, **kw)
if (m is not None) and (len(m) == len(x)):
paths = []
for marker in m:
if isinstance(marker, mmarkers.MarkerStyle):
marker_obj = marker
else:
marker_obj = mmarkers.MarkerStyle(marker)
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
paths.append(path)
sc.set_paths(paths)
return sc
X, y, X_train, X_test, y_train, y_test = load_dataset()
make_plot(X,y,"haha",' .svg')
2.네트워크 층수 의 영향
서로 다른 네트워크 깊이 에서 의 과 의합 정 도 를 탐구 하기 위해 우 리 는 모두 5 차례 의 훈련 실험 을 진행 했다.*119899*8712°[0,4]시 네트워크 층수 n+2 층 의 전 접속 층 네트워크 를 구축 하고 Adam 최적화 기 를 통 해 500 개의 Epoch 를 훈련 합 니 다.
def network_layers_influence(X_train, y_train):
# 5
for n in range(5):
#
model = Sequential()
#
model.add(layers.Dense(8, input_dim=2, activation='relu'))
# n , n+2
for _ in range(n):
model.add(layers.Dense(32, activation='relu'))
#
model.add(layers.Dense(1, activation='sigmoid'))
#
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
#
# x [-2, 3]
xx = np.arange(-2, 3, 0.01)
# y [-1.5, 2]
yy = np.arange(-1.5, 2, 0.01)
# x-y ,
XX, YY = np.meshgrid(xx, yy)
preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
print(preds)
title = " :{0}".format(2 + n)
file = " _%i.png" % (2 + n)
make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/network_layers')
3.Dropout 의 영향
드 로 풋 층 이 사 이 버 트 레이 닝 에 미 치 는 영향 을 살 펴 보기 위해 총 5 차례 의 실험 을 진 행 했 으 며,실험 마다 7 층 의 전 접속 층 네트워크 를 이용 해 훈련 했 으 나 전 접속 층 에 0~4 개의 드 로 풋 층 을 간격 으로 삽입 하고 아담 유 틸 리 티 를 통 해 500 개의 Epoch 를 훈련 했다.
def dropout_influence(X_train, y_train):
# 5 Dropout
for n in range(5):
#
model = Sequential()
#
model.add(layers.Dense(8, input_dim=2, activation='relu'))
counter = 0
# 5
for _ in range(5):
model.add(layers.Dense(64, activation='relu'))
# n Dropout
if counter < n:
counter += 1
model.add(layers.Dropout(rate=0.5))
#
model.add(layers.Dense(1, activation='sigmoid'))
#
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
#
model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
# Dropout
# x [-2, 3]
xx = np.arange(-2, 3, 0.01)
# y [-1.5, 2]
yy = np.arange(-1.5, 2, 0.01)
# x-y ,
XX, YY = np.meshgrid(xx, yy)
preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
title = " Dropout " if n == 0 else "{0} Dropout ".format(n)
file = "Dropout_%i.png" % n
make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/dropout')
4.정규 화의 영향
정규 화 계수 인 120582℃가 네트워크 모델 훈련 에 미 친 영향 을 탐구 하기 위해 우 리 는 L2 정규 화 방식 으로 5 층 의 신경 망 을 구축 했다.그 중에서 2,3,4 층 신경 망 층 의 가중치 장 량 W 는 모두 L2 정규 화 제약 항 을 추가 했다.
def build_model_with_regularization(_lambda):
#
model = Sequential()
model.add(layers.Dense(8, input_dim=2, activation='relu')) #
# 2-4 L2
model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
#
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #
return model
다음은 우선 가중치 시각 화 함 수 를 실현 합 니 다.
def plot_weights_matrix(model, layer_index, plot_name, file_name, output_dir=OUTPUT_DIR):
#
#
weights = model.layers[layer_index].get_weights()[0]
shape = weights.shape
#
X = np.array(range(shape[1]))
Y = np.array(range(shape[0]))
X, Y = np.meshgrid(X, Y)
# 3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
plt.title(plot_name, fontsize=20, fontproperties='SimHei')
#
ax.plot_surface(X, Y, weights, cmap=plt.get_cmap('rainbow'), linewidth=0)
#
ax.set_xlabel(' x ', fontsize=16, rotation=0, fontproperties='SimHei')
ax.set_ylabel(' y ', fontsize=16, rotation=0, fontproperties='SimHei')
ax.set_zlabel(' ', fontsize=16, rotation=90, fontproperties='SimHei')
#
plt.savefig(output_dir + "/" + file_name + ".svg")
plt.close(fig)
네트워크 구조 가 변 하지 않 는 조건 에서 우 리 는 정규 화 계 수 를 조절 하여 네트워크 의 훈련 효 과 를 테스트 하고 학습 모델 이 훈련 집에 서 의 결정 경계 곡선 을 그립 니 다.
def regularizers_influence(X_train, y_train):
for _lambda in [1e-5, 1e-3, 1e-1, 0.12, 0.13]: #
#
model = build_model_with_regularization(_lambda)
#
model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
#
layer_index = 2
plot_title = " :{}".format(_lambda)
file_name = " _" + str(_lambda)
#
plot_weights_matrix(model, layer_index, plot_title, file_name, output_dir=OUTPUT_DIR + '/regularizers')
#
# x [-2, 3]
xx = np.arange(-2, 3, 0.01)
# y [-1.5, 2]
yy = np.arange(-1.5, 2, 0.01)
# x-y ,
XX, YY = np.meshgrid(xx, yy)
preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
title = " :{}".format(_lambda)
file = " _%g.svg" % _lambda
make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/regularizers')
regularizers_influence(X_train, y_train)
텐 소 플 로 우의 과 의합 문 제 를 상세 하 게 풀 어 내 는 실전 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 텐 소 플 로 우 와 의합 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
GPU가 있는 M1 MacBook Air에 TensorFlow 설치(메탈)이제 TensorFlow v2.5에서 Apple의 tensorflow-metal PluggableDevice를 활용하여 Metal을 사용하여 Mac GPU에서 직접 가속화된 교육을 받을 수 있습니다. 자세히 알아보기...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.