以下是一个简单的神经网络模型,用于二元分类任务:

import numpy as np

class NeuralNetwork: def init(self, input_dim, hidden_dim, output_dim): self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim # 随机初始化权重矩阵 self.weights1 = np.random.randn(input_dim, hidden_dim) self.weights2 = np.random.randn(hidden_dim, output_dim)

def sigmoid(self, x):
    return 1 / (1 + np.exp(-x))

def forward(self, X):
    self.hidden_layer = self.sigmoid(np.dot(X, self.weights1))
    self.output_layer = self.sigmoid(np.dot(self.hidden_layer, self.weights2))
    return self.output_layer

def sigmoid_derivative(self, x):
    return x * (1 - x)

def backward(self, X, y, learning_rate):
    # 计算输出层的误差
    output_error = y - self.output_layer
    output_delta = output_error * self.sigmoid_derivative(self.output_layer)
    # 计算隐藏层的误差
    hidden_error = np.dot(output_delta, self.weights2.T)
    hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer)
    # 更新权重矩阵
    self.weights2 += learning_rate * np.dot(self.hidden_layer.T, output_delta)
    self.weights1 += learning_rate * np.dot(X.T, hidden_delta)

def train(self, X, y, epochs, learning_rate):
    for i in range(epochs):
        output = self.forward(X)
        self.backward(X, y, learning_rate)

def predict(self, X):
    return np.round(self.forward(X))

测试模型

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([[0], [1], [1], [0]]) model = NeuralNetwork(2, 3, 1) model.train(X, y, 10000, 0.1) print(model.predict(X))

使用python编写一个神经网络模型

原文地址: https://www.cveoy.top/t/topic/DoY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录