def _numerical_gradient_1d(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[idx] = float(tmp_val) + h fxh1 = f(x) # f(x+h) x[idx] = tmp_val - h fxh2 = f(x) # f(x-h) grad[idx] = (fxh1 - fxh2) / (2*h) x[idx] = tmp_val # 还原值 return grad
时间: 2024-04-03 15:37:00 浏览: 17
这是数值微分(numerical differentiation)的函数,用于求解一元函数在某一点的导数。数值微分是一种通过有限差分近似求解函数导数的方法,其基本思想是在某一点 x 处,通过计算函数在 x+h 和 x-h 两个点处的函数值,再用差分近似求解函数在 x 处的导数。这里的 h 为一个极小的数值,通常取 0.0001。
_numerical_gradient_1d 函数实现了一元函数的数值微分,输入参数包括函数 f 和点 x,输出为函数在点 x 处的导数。函数首先初始化一个与 x 相同形状的导数数组 grad,然后对于 x 向量中的每个元素,分别计算 x+h 和 x-h 处的函数值,再用差分近似求解该元素上的导数,最终得到整个向量在 x 处的导数。
相关问题
def numerical_gradient_2d(f, X): if X.ndim == 1: return _numerical_gradient_1d(f, X) else: grad = np.zeros_like(X) for idx, x in enumerate(X): grad[idx] = _numerical_gradient_1d(f, x) return grad
这是数值微分的另一个函数,用于求解二元函数在某一点的梯度。与一元函数不同,二元函数的梯度是一个向量,包含了函数在每个自变量上的偏导数。数值微分求解二元函数的梯度的方法与一元函数类似,只需对每个自变量分别进行数值微分,即可得到整个向量在该点处的梯度。
numerical_gradient_2d 函数实现了二元函数的数值微分,输入参数包括函数 f 和点 X,输出为函数在点 X 处的梯度。函数首先判断输入点 X 的维度,如果是一维向量则调用 _numerical_gradient_1d 函数求解一元函数的导数,如果是二维矩阵则对矩阵中的每个向量分别调用 _numerical_gradient_1d 函数求解二元函数在该向量上的梯度,最终得到整个矩阵在该点处的梯度。
误差反向传播法的实现 输出使用后4000个样本训练得到模型在测试集上的结果,参数设置为:batch:300;iters_num:2000;lambda:0.1
误差反向传播法(Backpropagation)是一种常用的神经网络训练方法,它通过计算神经网络输出与真实标签之间的误差,然后根据误差大小来更新神经网络中的参数。
具体实现步骤如下:
1. 初始化神经网络参数,包括权重和偏置。
2. 从训练数据中随机选择一批样本(batch),将这些样本输入神经网络,计算输出结果。
3. 计算输出结果与真实标签之间的误差,使用误差函数(如均方误差)来衡量误差大小。
4. 根据误差大小来计算梯度,即误差对于每个参数的偏导数。
5. 使用梯度下降法来更新神经网络中的参数,即将每个参数的值减去对应的学习率乘以梯度。
6. 重复步骤2-5,直到达到指定的迭代次数(iters_num)或误差达到指定的阈值。
代码实现如下:
```
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_grad(x):
return (1 - sigmoid(x)) * sigmoid(x)
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size):
self.params = {}
self.params['W1'] = 0.01 * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = 0.01 * np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
def predict(self, x):
W1, b1, W2, b2 = self.params['W1'], self.params['b1'], self.params['W2'], self.params['b2']
z1 = np.dot(x, W1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, W2) + b2
y = z2
return y
def loss(self, x, t):
y = self.predict(x)
loss = np.mean((y - t) ** 2) + 0.5 * lambda_reg * (np.sum(self.params['W1'] ** 2) + np.sum(self.params['W2'] ** 2))
return loss
def accuracy(self, x, t):
y = self.predict(x)
accuracy = np.mean((y > 0.5) == (t == 1)) * 100
return accuracy
def numerical_gradient(self, x, t):
h = 1e-4
grads = {}
for param_name in self.params:
param = self.params[param_name]
grad = np.zeros_like(param)
for i in range(param.shape[0]):
for j in range(param.shape[1]):
tmp_val = param[i,j]
param[i,j] = tmp_val + h
f1 = self.loss(x, t)
param[i,j] = tmp_val - h
f2 = self.loss(x, t)
grad[i,j] = (f1 - f2) / (2 * h)
param[i,j] = tmp_val
grads[param_name] = grad
return grads
def gradient(self, x, t):
W1, b1, W2, b2 = self.params['W1'], self.params['b1'], self.params['W2'], self.params['b2']
grads = {}
batch_num = x.shape[0]
# forward
z1 = np.dot(x, W1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, W2) + b2
y = z2
# backward
delta2 = y - t
grads['W2'] = np.dot(a1.T, delta2)
grads['b2'] = np.sum(delta2, axis=0)
delta1 = np.dot(delta2, W2.T) * sigmoid_grad(z1)
grads['W1'] = np.dot(x.T, delta1)
grads['b1'] = np.sum(delta1, axis=0)
# add regularization
grads['W2'] += lambda_reg * W2
grads['W1'] += lambda_reg * W1
return grads
def fit(self, x_train, y_train, x_test, y_test, batch_size=100, epochs=10, learning_rate=0.1, lambda_reg=0.1):
self.lambda_reg = lambda_reg
train_loss_list = []
train_acc_list = []
test_acc_list = []
train_size = x_train.shape[0]
iter_per_epoch = max(train_size / batch_size, 1)
for epoch in range(epochs):
perm = np.random.permutation(train_size)
for i in range(0, train_size, batch_size):
x_batch = x_train[perm[i:i+batch_size]]
y_batch = y_train[perm[i:i+batch_size]]
grads = self.gradient(x_batch, y_batch)
for param_name in self.params:
self.params[param_name] -= learning_rate * grads[param_name]
train_loss = self.loss(x_train, y_train)
train_loss_list.append(train_loss)
train_acc = self.accuracy(x_train, y_train)
train_acc_list.append(train_acc)
test_acc = self.accuracy(x_test, y_test)
test_acc_list.append(test_acc)
print("epoch: %d, train_loss: %f, train_acc: %f, test_acc: %f" % (epoch+1, train_loss, train_acc, test_acc))
return train_loss_list, train_acc_list, test_acc_list
# 读取数据
x_train = np.load('x_train.npy')
y_train = np.load('y_train.npy')
x_test = np.load('x_test.npy')
y_test = np.load('y_test.npy')
# 构建神经网络模型
input_size = x_train.shape[1]
hidden_size = 100
output_size = 1
net = TwoLayerNet(input_size, hidden_size, output_size)
# 训练神经网络模型
batch_size = 300
iters_num = 2000
lambda_reg = 0.1
train_loss_list, train_acc_list, test_acc_list = net.fit(x_train, y_train, x_test, y_test, batch_size, iters_num, lambda_reg)
# 输出测试集结果
test_acc = net.accuracy(x_test, y_test)
print("Test accuracy: %f" % test_acc)
```
在输出后4000个样本训练得到模型在测试集上的结果时,我们只需要将训练集中的前4000个样本用来训练模型,然后再使用测试集来测试模型的准确率即可。具体代码如下:
```
# 取出训练集中的前4000个样本
x_train = x_train[:4000]
y_train = y_train[:4000]
# 训练神经网络模型
batch_size = 300
iters_num = 2000
lambda_reg = 0.1
train_loss_list, train_acc_list, test_acc_list = net.fit(x_train, y_train, x_test, y_test, batch_size, iters_num, lambda_reg)
# 输出测试集结果
test_acc = net.accuracy(x_test, y_test)
print("Test accuracy: %f" % test_acc)
```