歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java實現隨機抽樣

Java實現隨機抽樣

日期:2017/3/1 10:41:04   编辑:Linux編程
編程實現對數據記錄的隨機抽樣。給定概率p,依概率p對給定的數據集合進行隨機抽樣。

比如說現在在一個數組中存放了10000位同學的身高和體重信息,現在需要你對這100位同學以概率p=0.002進行抽樣,隨機取出這10000位同學中約20位同學的信息。

  1. import java.io.BufferedReader;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.LineNumberReader;
  5. import java.util.Random;
  6. import java.util.Scanner;
  7. import java.io.InputStreamReader;
  8. public class ReadSelectedLine {
  9. // 讀取制定行
  10. static void readLineVarFile(String fileName, int lineNumber)
  11. throws IOException {
  12. BufferedReader reader = new BufferedReader(new InputStreamReader(
  13. new FileInputStream(fileName)));
  14. String line = reader.readLine();
  15. int num = 0;
  16. while (line != null) {
  17. if (lineNumber == ++num) {
  18. System.out.println("line " + lineNumber + ": " + line);
  19. }
  20. line = reader.readLine();
  21. }
  22. reader.close();
  23. }
  24. // 文件內容的總行數。
  25. static int getTotalLines(String fileName) throws IOException {
  26. BufferedReader in = new BufferedReader(new InputStreamReader(
  27. new FileInputStream(fileName)));
  28. LineNumberReader reader = new LineNumberReader(in);
  29. String s = reader.readLine();
  30. int lines = 0;
  31. while (s != null) {
  32. lines++;
  33. s = reader.readLine();
  34. }
  35. reader.close();
  36. in.close();
  37. return lines;
  38. }
  39. public static void main(String[] args) throws IOException {
  40. // 讀取文件
  41. String fileName = "D:/student_info.txt";
  42. // 獲取文件的內容的總行數
  43. int totalNo = getTotalLines(fileName);
  44. System.out.println("There are " + totalNo + " lines in the text!");
  45. System.out.print("input the /"gailv/"(0.0-1.0): ");
  46. Scanner scanner = new Scanner(System.in);
  47. float gailv = scanner.nextFloat();
  48. int del_num = (int) (totalNo * gailv);
  49. for (int i = 0; i < del_num; i++) {
  50. Random rand = new Random();
  51. // 指定讀取的行號
  52. int lineNumber = (int) (rand.nextDouble() * totalNo);
  53. // 讀取指定行的內容
  54. readLineVarFile("d:/student_info.txt", lineNumber);
  55. }
  56. }
  57. }

(注意:外部文件的文件名與路徑)

關於隨機抽樣算法,我采用的是,先通過讀取外部文件(存放需要進行隨機抽樣信息的文件),然後統計出該文件的行數(前提是需要抽樣的樣本必須是每一行存放一條對應信息),再通過隨機算法產生出需要抽取的樣本所對應的行號(通過輸入抽樣概率,計算出樣本),最後輸出隨機抽樣結果。本程序使用循環覆蓋所讀取文件的內容,可以很好解決內存消耗問題。

Copyright © Linux教程網 All Rights Reserved