python写softmax分类三类平面上的二维点的代码
时间: 2024-05-08 18:19:25 浏览: 148
MLP分类_softmax分类器_keras_神经网络_establishjop_分类_
好的,以下是Python写softmax分类三类平面上的二维点的代码:
```python
import numpy as np
# 随机生成三类平面上的二维点
num_points = 100
dimensions = 2
points = np.random.randint(0, 100, [num_points, dimensions])
labels = np.random.randint(0, 3, [num_points, 1])
# 将标签转化为独热编码
one_hot_labels = np.zeros((num_points, 3))
for i in range(num_points):
one_hot_labels[i, labels[i]] = 1
# 初始化权重矩阵和偏置向量
weights = np.random.randn(dimensions, 3)
biases = np.zeros((1, 3))
# 定义softmax函数
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis=0)
# 定义交叉熵损失函数
def cross_entropy_loss(predicted, actual):
loss = -np.sum(actual * np.log(predicted))
return loss
# 定义学习率和训练次数
learning_rate = 0.01
epochs = 1000
# 训练模型
for epoch in range(epochs):
# 前向传播
predicted = np.dot(points, weights) + biases
predicted = softmax(predicted)
# 计算损失
loss = cross_entropy_loss(predicted, one_hot_labels)
# 反向传播
error = predicted - one_hot_labels
dw = np.dot(points.T, error)
db = np.sum(error, axis=0, keepdims=True)
# 更新权重和偏置
weights -= learning_rate * dw
biases -= learning_rate * db
# 每100次迭代输出一次损失
if epoch % 100 == 0:
print('Epoch %d loss: %.4f' % (epoch, loss))
```
希望对您有帮助!
阅读全文