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.bias1 = np.zeros((1, hidden_dim)) self.weights2 = np.random.randn(hidden_dim, output_dim) self.bias2 = np.zeros((1, output_dim)) def relu(self, x): return np.maximum(0, x) def relu_derivative(self, x): return np.where(x >= 0, 1, 0) def forward(self, x): self.z1 = np.dot(x, self.weights1) + self.bias1 self.a1 = self.relu(self.z1) self.z2 = np.dot(self.a1, self.weights2) + self.bias2 self.y_hat = self.z2 return self.y_hat def backward(self, x, y, learning_rate): error = self.y_hat - y delta2 = error delta1 = np.dot(delta2, self.weights2.T) * self.relu_derivative(self.a1) grad_weights2 = np.dot(self.a1.T, delta2) grad_bias2 = np.sum(delta2, axis=0, keepdims=True) grad_weights1 = np.dot(x.T, delta1) grad_bias1 = np.sum(delta1, axis=0) self.weights2 -= learning_rate * grad_weights2 self.bias2 -= learning_rate * grad_bias2 self.weights1 -= learning_rate * grad_weights1 根据代码加上损失函数和优化
时间: 2024-03-12 15:43:51 浏览: 118
函数,可以将这个神经网络变为完整的模型。一种常见的损失函数是均方误差(Mean Squared Error),可以用于回归问题:
```python
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.bias1 = np.zeros((1, hidden_dim))
self.weights2 = np.random.randn(hidden_dim, output_dim)
self.bias2 = np.zeros((1, output_dim))
def relu(self, x):
return np.maximum(0, x)
def relu_derivative(self, x):
return np.where(x >= 0, 1, 0)
def forward(self, x):
self.z1 = np.dot(x, self.weights1) + self.bias1
self.a1 = self.relu(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.y_hat = self.z2
return self.y_hat
def backward(self, x, y, learning_rate):
error = self.y_hat - y
delta2 = error
delta1 = np.dot(delta2, self.weights2.T) * self.relu_derivative(self.a1)
grad_weights2 = np.dot(self.a1.T, delta2)
grad_bias2 = np.sum(delta2, axis=0, keepdims=True)
grad_weights1 = np.dot(x.T, delta1)
grad_bias1 = np.sum(delta1, axis=0)
self.weights2 -= learning_rate * grad_weights2
self.bias2 -= learning_rate * grad_bias2
self.weights1 -= learning_rate * grad_weights1
self.bias1 -= learning_rate * grad_bias1
def mse_loss(self, y, y_hat):
return np.mean((y - y_hat)**2)
def sgd_optimizer(self, x, y, learning_rate):
y_hat = self.forward(x)
loss = self.mse_loss(y, y_hat)
self.backward(x, y, learning_rate)
return loss
```
在这个模型中,我们添加了 `mse_loss` 函数,用于计算均方误差,同时添加了 `sgd_optimizer` 函数,用于执行随机梯度下降优化算法。在每次迭代中,我们计算预测值 `y_hat`,然后计算损失值并执行反向传播算法更新神经网络的权重和偏置。最后,我们返回损失值作为当前迭代的结果。根据需要,我们可以使用其他损失函数和优化器来训练这个神经网络。
阅读全文