gpt4 book ai didi

machine-learning - Keras 模型为 make_moons 数据创建线性分类

转载 作者:行者123 更新时间:2023-11-30 08:37:15 31 4
gpt4 key购买 nike

我正在尝试重现此 WildML - Implementing a Neural Network From Scratch 中的模型教程,但使用 Keras 代替。我尝试使用与教程相同的所有配置,但即使在调整时期数、批量大小、激活函数和隐藏层中的单元数之后,我仍然得到线性分类:

classification graph

这是我的代码:

from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.utils.visualize_util import plot
from keras.utils.np_utils import to_categorical

import numpy as np
import matplotlib.pyplot as plt

import sklearn
from sklearn import datasets, linear_model

# Build model
model = Sequential()
model.add(Dense(input_dim=2, output_dim=3, activation="tanh", init="normal"))
model.add(Dense(output_dim=2, activation="softmax"))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# Train
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)
y_binary = to_categorical(y)
model.fit(X, y_binary, nb_epoch=100)

# Helper function to plot a decision boundary.
# If you don't fully understand this function don't worry, it just generates the contour plot below.
def plot_decision_boundary(pred_func):
# Set min and max values and give it some padding
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Predict the function value for the whole gid
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)

# Predict and plot
plot_decision_boundary(lambda x: model.predict_classes(x, batch_size=200))
plt.title("Decision Boundary for hidden layer size 3")
plt.show()

最佳答案

我相信我已经解决了这个问题。如果我删除 np.random.seed(0) 并训练 2000 个 epoch,输出并不总是线性的,有时会达到 90% 以上的准确度:

enter image description here

肯定是 np.random.seed(0) 导致参数播种效果不佳,而且由于我正在修复随机播种,所以每次都会看到相同的图表。

关于machine-learning - Keras 模型为 make_moons 数据创建线性分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719308/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com