【简单算法】37.Shuffle an Array

题目:

打乱一个没有重复元素的数组。

示例:

// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。
solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();

解题思路:

reset操作:

记录下数组的原始位置,reset操作时,直接返回原数组的拷贝即可。

shuffle:

将数组中的每个数与数组中的随机位置进行交换即可。关键点在于如何找到随机交换的位置,并且保证概率相同。

及第i个数可能与数组中任意一个数进行交换。

int t = (i + rand()%res.size())%(res.size());

 

 

代码:

class Solution {
public:
    Solution(vector<int> nums) {
        v.insert(v.begin(), nums.begin(), nums.end());
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return v;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> res = v;
        for (int i = 0; i < res.size(); ++i) {
            int t = i + rand() % (res.size() - i);
            swap(res[i], res[t]);
        }
        
        return res;
    }
private:
    vector<int> v;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * vector<int> param_1 = obj.reset();
 * vector<int> param_2 = obj.shuffle();
 */

 

转载于:https://www.cnblogs.com/mikemeng/p/9000039.html

### 使用SVM算法实现MNIST数据集的手写数字识别 #### 导入必要的库 为了使用支持向量机(SVM)对MNIST数据集进行手写数字识别,首先需要导入一些基本的Python库以及Scikit-Learn中的SVM模块。 ```python import numpy as np from sklearn import datasets, metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC ``` #### 加载并准备数据 接着加载MNIST数据集,并对其进行标准化处理。由于MNIST数据集中每张图像是28x28像素大小,因此通常会将其展平成784维的一维数组作为输入特征[^3]。 ```python # Load the dataset digits = datasets.load_digits() # Flatten the images into a 1D array of pixels per image. n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) # Split data into training and test sets X_train, X_test, y_train, y_test = train_test_split( data, digits.target, test_size=0.5, shuffle=True) # Scale features to have zero mean and unit variance scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) ``` #### 训练SVM模型 创建一个`SVC`实例来定义SVM分类器,在此例子中选择了径向基函数(RBF)作为核函数。当然也可以尝试其他类型的核函数如线性或多项式等。之后调用`.fit()`方法开始训练过程[^4]。 ```python # Create an instance of SVM Classifier with RBF kernel classifier = SVC(kernel='rbf', gamma=0.001, C=100.) # Train the classifier on the training set classifier.fit(X_train, y_train) ``` #### 测试与评估模型性能 完成训练后,可以通过预测测试集上的标签并与真实值对比来计算准确率和其他评价指标。此外还可以绘制混淆矩阵以便更直观地理解错误分布情况[^5]。 ```python # Predict target values for samples in the testing set predicted = classifier.predict(X_test) # Print classification report showing precision, recall, f-score etc. print(f"Classification report:\n{metrics.classification_report(y_test, predicted)}") # Plot confusion matrix disp = metrics.ConfusionMatrixDisplay.from_predictions(y_test, predicted) disp.figure_.suptitle("Confusion Matrix") plt.show() ``` 以上就是使用SVM算法针对MNIST数据集执行手写数字识别的主要流程概述。值得注意的是实际应用过程中可能还需要进一步调整参数以获得更好的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值