在Python中使用tanh()激活函数进行神经网络的训练与预测
发布时间:2023-12-24 06:17:22
在Python中,可以使用tanh()激活函数进行神经网络的训练和预测。tanh()是双曲正切函数,它的输出范围为[-1, 1]。相比于sigmoid函数,tanh函数输出的值范围更广,更容易产生梯度,因此在神经网络中更常用。
下面是在Python中使用tanh()激活函数进行神经网络的训练和预测的示例:
首先,我们需要导入所需的库:
import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_classification from sklearn.metrics import accuracy_score
然后,我们可以使用make_classification函数生成一个用于训练的虚拟数据集:
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)
接下来,我们需要对数据进行划分并进行标准化处理:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test)
现在,我们可以定义一个简单的神经网络模型,并使用tanh()作为激活函数。在这个例子中,我们使用一个隐藏层,该层有50个神经元:
class NeuralNetwork:
def __init__(self):
self.weights1 = np.random.randn(10, 50)
self.weights2 = np.random.randn(50, 1)
def forward(self, X):
self.hidden = tanh(np.dot(X, self.weights1))
self.output = tanh(np.dot(self.hidden, self.weights2))
return self.output
def backward(self, X, y, learning_rate):
error = y - self.output
error_output = error * tanh_derivative(self.output)
error_hidden = np.dot(error_output, self.weights2.T) * tanh_derivative(self.hidden)
self.weights2 += learning_rate * np.dot(self.hidden.T, error_output)
self.weights1 += learning_rate * np.dot(X.T, error_hidden)
接下来,定义tanh()和tanh_derivative()函数:
def tanh(x):
return np.tanh(x)
def tanh_derivative(x):
return 1 - np.tanh(x) ** 2
然后,我们可以使用神经网络进行训练和预测:
nn = NeuralNetwork()
for i in range(1000):
nn.forward(X_train)
nn.backward(X_train, y_train, learning_rate=0.01)
# 预测
y_pred = np.round(nn.forward(X_test))
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
这是一个简单的使用tanh()激活函数的神经网络训练和预测的例子。通过改变隐藏层的大小、调整迭代次数和学习率等超参数,可以进一步改进模型的性能。
