np.random.permutation()解析

本文详细解析了np.random.permutation函数的使用方法,包括对一维和多维数据的随机排序示例。对于多维数据,该函数仅在第一维度上进行随机排序,即对于3×3矩阵,仅对行进行随机排序。

np.random.permutation():随机排列序列。

例1:对0-5之间的序列进行随机排序

在这里插入图片描述

例2:对一个list进行随机排序

在这里插入图片描述

多维度的咋回事?

来看一个例子:
在这里插入图片描述
a矩阵输出为:

在这里插入图片描述
现在看c矩阵,我运行了两次:
第一次运行结果:
在这里插入图片描述
然后,我又运行了一次:
在这里插入图片描述
通过这个例子可以看出,对于一个多维的输入,只是在第一维上进行了随机排序。
对这个这个3×3矩阵来说,只是对行进行随机排序。

import numpy as np import random import matplotlib.pyplot as plt # 需要安装但用户允许的可视化库 # 生成线性可分数据 def generate_data(n_samples=100): np.random.seed(42) X1 = np.random.randn(n_samples//2, 2) + np.array([2, 2]) # 类别1 X2 = np.random.randn(n_samples//2, 2) + np.array([-2, -2]) # 类别-1 X = np.vstack((X1, X2)) y = np.array([1]*(n_samples//2) + [-1]*(n_samples//2)) indices = np.random.permutation(len(X)) # 打乱索引保证数据一致性[^1] return X[indices], y[indices] # 划分训练集和测试集 def train_test_split(X, y, test_ratio=0.2): split_idx = int(len(X)*(1-test_ratio)) return X[:split_idx], X[split_idx:], y[:split_idx], y[split_idx:] # 感知机实现 class Perceptron: def __init__(self, n_features): self.weights = np.random.uniform(-1, 1, n_features) # numpy向量化初始化 self.bias = 0.0 def predict(self, X): return np.where(np.dot(X, self.weights) + self.bias >= 0, 1, -1) def train(self, X_train, y_train, epochs=100, lr=0.1): for _ in range(epochs): for i in range(len(X_train)): x, y_true = X_train[i], y_train[i] y_pred = self.predict(x.reshape(1, -1))[0] if y_pred != y_true: update = lr * (y_true - y_pred) self.weights += update * x # numpy向量化更新 self.bias += update # 计算准确率 def calculate_accuracy(model, X, y): predictions = model.predict(X) return np.mean(predictions == y) * 100 # 直接使用numpy计算准确率[^3] # 绘制决策边界 def plot_decision_boundary(model, X, y): plt.scatter(X[:,0], X[:,1], c=y, cmap='bwr', edgecolors='k') x_min, x_max = X[:,0].min()-1, X[:,0].max()+1 w1, w2 = model.weights b = model.bias x_values = np.linspace(x_min, x_max, 100) y_values = (-w1 * x_values - b) / w2 # 决策边界方程: w1x1 + w2x2 + b = 0 plt.plot(x_values, y_values, 'g--', lw=2) plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Decision Boundary') plt.show() # 主流程 if __name__ == "__main__": X, y = generate_data(200) X_train, X_test, y_train, y_test = train_test_split(X, y) model = Perceptron(n_features=2) model.train(X_train, y_train, epochs=50) train_acc = calculate_accuracy(model, X_train, y_train) test_acc = calculate_accuracy(model, X_test, y_test) print(f"训练准确率: {train_acc:.1f}%") print(f"测试准确率: {test_acc:.1f}%") print(f"学习到的权重: {model.weights}") print(f"偏置项: {model.bias}") plot_decision_boundary(model, X_train, y_train)不适用matplotlib库请修改
最新发布
05-11
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值