In [1]:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# define the XOR input and output data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# build the neural network model
model = Sequential()
model.add(Dense(2, activation='relu')) # hidden layer with 2 neurons
model.add(Dense(1, activation='sigmoid')) # output layer with 1 neuron
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# train the model
model.fit(X, y, epochs=10000, verbose=0)
# evaluate the model
loss, accuracy = model.evaluate(X, y)
print(f"accuracy: {accuracy * 100:.2f}%")
# make predictions
predictions = model.predict(X)
predictions = np.round(predictions).astype(int)
print("predictions:")
for i in range(len(X)):
print(f"input: {X[i]} => predicted output: {predictions[i]}, actual output: {y[i]}")
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 53ms/step - accuracy: 1.0000 - loss: 0.0013 accuracy: 100.00% 1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 19ms/step predictions: input: [0 0] => predicted output: [0], actual output: [0] input: [0 1] => predicted output: [1], actual output: [1] input: [1 0] => predicted output: [1], actual output: [1] input: [1 1] => predicted output: [0], actual output: [0]
In [2]:
model.weights
Out[2]:
[<Variable path=sequential/dense/kernel, shape=(2, 2), dtype=float32, value=[[-3.234061 3.3131413] [ 3.2338295 -3.3131545]]>, <Variable path=sequential/dense/bias, shape=(2,), dtype=float32, value=[-0.00017982 -0.00036467]>, <Variable path=sequential/dense_1/kernel, shape=(2, 1), dtype=float32, value=[[ 4.1856656 ] [ 3.9753308 ]]>, <Variable path=sequential/dense_1/bias, shape=(1,), dtype=float32, value=[-5.779532]>]
In [3]:
def sigmoid(x):
return 1 / (1 + np.exp(-x))
