softmax 分类实现代码
时间: 2025-06-16 07:40:24 浏览: 12
以下是实现 Softmax 分类算法的一个简单 Python 示例代码:
### 软件环境准备
为了运行以下代码,需安装 NumPy 库。如果尚未安装,可以通过 `pip install numpy` 安装。
### Softmax 函数定义
Softmax 是一种将实数值转换为概率分布的函数,其核心公式如下:
\[
S(y_i) = \frac{e^{y_i}}{\sum_{j=1}^{n}{e^{y_j}}}
\]
其中 \( y_i \) 表示输入向量中的第 i 个元素,\( n \) 表示输入向量的长度。
下面是具体的实现代码:
```python
import numpy as np
def softmax(x):
"""
计算softmax值
:param x: 输入数组 (numpy array),形状可以是一维或多维
:return: 经过softmax变换后的数组
"""
# 防止溢出,减去最大值以稳定指数运算
e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
return e_x / np.sum(e_x, axis=-1, keepdims=True)
# 测试数据
input_data = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
output = softmax(input_data)
print("Input Data:\n", input_data)
print("Output of Softmax Function:\n", output)
```
这段代码实现了 Softmax 的基本功能,并考虑了数值稳定性问题[^1]。具体来说,在计算过程中会先减去每行的最大值,从而防止因指数操作而导致的数值溢出。
### 使用 Softmax 进行分类预测
下面是一个简单的例子,展示如何利用 Softmax 对一组未归一化的分数进行分类预测:
```python
class SimpleClassifier:
def __init__(self, weights, bias=None):
self.weights = weights
self.bias = bias if bias is not None else np.zeros(weights.shape[0])
def predict(self, inputs):
z = np.dot(inputs, self.weights.T) + self.bias
probabilities = softmax(z)
return probabilities.argmax(axis=1), probabilities
# 初始化权重矩阵和偏置项
weights = np.random.rand(3, 2) # 假设有两个特征,三个类别
bias = np.random.rand(3)
classifier = SimpleClassifier(weights, bias)
# 构造测试样本集
test_samples = np.array([
[0.5, 0.8],
[-0.2, 0.9]
])
predictions, probabilities = classifier.predict(test_samples)
for sample_idx, prediction in enumerate(predictions):
print(f"Sample {sample_idx}: Predicted Class={prediction}, Probabilities={probabilities[sample_idx]}")
```
以上代码展示了如何构建一个简易的线性分类器并使用 Softmax 来完成多分类任务[^1]。
---
####
阅读全文
相关推荐

















