简单的全连接神经网络python代码
时间: 2023-09-03 20:07:01 浏览: 152
Sure, here's a simple example of a fully connected neural network in Python:
```
import numpy as np
# Define the sigmoid activation function
def sigmoid(x):
return 1/(1+np.exp(-x))
# Define the derivative of the sigmoid function
def sigmoid_derivative(x):
return x*(1-x)
# Define the input dataset
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
# Define the output dataset
y = np.array([[0],[1],[1],[0]])
# Set the random seed
np.random.seed(1)
# Initialize the weights randomly with mean 0
synaptic_weights = 2*np.random.random((3,1)) - 1
# Train the neural network
for i in range(20000):
# Forward propagation
layer0 = X
layer1 = sigmoid(np.dot(layer0,synaptic_weights))
# Calculate the error
layer1_error = y - layer1
# Multiply the error by the slope of the sigmoid at the values in layer1
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# Update the weights
synaptic_weights += np.dot(layer0.T,layer1_delta)
# Print the final output
print("Output after training:",layer1)
```
This neural network has one hidden layer with three neurons and uses the sigmoid activation function. The output is binary, with values of either 0 or 1. The network is trained on a small dataset (X) with corresponding labels (y) using stochastic gradient descent (SGD).
阅读全文