训练数据取自两个不同半径的圆
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
import numpy as np
from matplotlib.pyplot import plot
%matplotlib inline
data = [ [np.cos(d), np.sin(d), 1, 0] for d in np.linspace(0,np.pi*2)] + [ [np.cos(d)*2, np.sin(d)*2, 0, 1] for d in np.linspace(0,np.pi*2)]
X = np.array(data)[:, 0:2]
y = np.array(data)[:, 2]
plot(X[y==0][:,0], X[y==0][:,1], '.')
plot(X[y==1][:,0], X[y==1][:,1], '.')
训练模型是两层神经网络
model = Sequential()
model.add(Dense(4, activation='relu', input_shape=(2,)))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='mean_squared_error', optimizer="SGD")
model.fit(X, y, epochs=2000, verbose=0)
训练得到的判定边界是个多边形,真的能分割两个圆
l = np.linspace(-2,2,num=100)
X_test = []
for i in range(len(l)):
for j in range(len(l)):
X_test.append([l[i], l[j]])
X_test = np.matrix(X_test)
p = model.predict(X_test).flatten()
p[p<.5] = 0
p[p>=.5] = 1
plot(X_test[p==0][:,0], X_test[p==0][:,1], '*')
plot(X_test[p==1][:,0], X_test[p==1][:,1], '*')
plot(X[y==0][:,0], X[y==0][:,1], '.')
plot(X[y==1][:,0], X[y==1][:,1], '.')