使用NumPy构建神经网络:Python实现
import numpy as np
定义激活函数
def sigmoid(x): return 1 / (1 + np.exp(-x))
定义神经网络类
class NeuralNetwork: def init(self, input_size, output_size): self.input_size = input_size self.output_size = output_size
# 初始化权重和偏置
self.weights1 = np.random.randn(self.input_size, self.output_size)
self.bias1 = np.random.randn(self.output_size)
def forward(self, X):
# 前向传播
self.z = np.dot(X, self.weights1) + self.bias1
self.output = sigmoid(self.z)
return self.output
def backward(self, X, y, output):
# 反向传播
self.error = output - y
self.gradient = sigmoid(self.z) * (1 - sigmoid(self.z))
self.weights1 -= np.dot(X.T, self.error * self.gradient)
self.bias1 -= np.sum(self.error * self.gradient, axis=0)
def train(self, X, y, epochs):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
output = self.forward(X)
predictions = np.round(output)
return predictions
创建神经网络对象
nn = NeuralNetwork(2, 3)
定义输入和输出数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
训练神经网络
nn.train(X, y, epochs=10000)
预测新数据
new_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) predictions = nn.predict(new_data) print(predictions)
要将数据替换为本地的Excel文件,你需要使用适当的库来读取Excel文件,并将数据转换为NumPy数组。以下是一种可能的方法使用pandas库来读取Excel文件并将数据转换为NumPy数组:
import pandas as pd
import numpy as np
# 读取Excel文件
data = pd.read_excel('your_file.xlsx')
# 将数据转换为NumPy数组
X = data.iloc[:, :2].values
y = data.iloc[:, 2:].values
# 创建神经网络对象
nn = NeuralNetwork(2, 3)
# 训练神经网络
nn.train(X, y, epochs=10000)
# 预测新数据
new_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = nn.predict(new_data)
print(predictions)
请确保将your_file.xlsx替换为你的Excel文件的路径。此外,还需要确保Excel文件中的数据与神经网络的输入和输出大小匹配。
原文地址: https://www.cveoy.top/t/topic/fM4s 著作权归作者所有。请勿转载和采集!