Question

I was running a CVS file using KNN(java) to find and calculate the shortest distance with the desired K.

| ID f 2 3 4 5 6 7 8 9 10 11 12 13 14 f15 t | 0 0 0 0 0 0 0 2.5 0 0 0 0 0 0 0 | 0.31 0 0.63 1.91 0.21 0 0 0 0.42 0.1 0 0.31 0This is the screenshot with 57 columns, goes from f1 to f57.

The following is then my code when you run it you will get NumberFormat error. Why is that happening? What should I change?

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.io.FileNotFoundException;

class Knn {

static class Sample {

int label;

int [] pixels;

}

private static List<Sample> readFile(String file) throws IOException {

List<Sample> samples = new ArrayList<Sample>();

BufferedReader reader = new BufferedReader(new FileReader(file));

try {

String line = reader.readLine(); // ignore header

while((line = reader.readLine()) != null)

{

String[] tokens = line.split(",");

Sample sample = new Sample();

sample.label = Integer.parseInt(tokens[0]);

sample.pixels = new int[tokens.length - 1];

for(int i = 1; i < tokens.length; i++)

{

sample.pixels[i-1] = Integer.parseInt(tokens[i]);

}

samples.add(sample);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally { reader.close(); }

return samples;

}

private static int distance(int[] a, int[] b) {

int sum = 0;

for(int i = 0; i < a.length; i++) {

sum += (a[i] - b[i]) * (a[i] - b[i]);

}

return (int)Math.sqrt(sum); // euclidian distance would be sqrt(sum)...

}

private static int classify(List<Sample> trainingSet, int[] pixels) {

int label = 0, bestDistance = Integer.MAX_VALUE;

for(Sample sample: trainingSet) {

int dist = distance(sample.pixels, pixels);

if(dist < bestDistance) {

bestDistance = dist;

label = sample.label;

}

}

return label;

}

public static void main(String[] argv) throws IOException {

List<Sample> trainingSet = readFile("/Users/gary/Desktop/spam_train.csv");

List<Sample> validationSet = readFile("/Users/gary/Desktop/spam_test.csv");

int numCorrect = 0;

for(Sample sample:validationSet)

{

if(classify(trainingSet, sample.pixels) == sample.label) numCorrect++;

}

System.out.println("Accuracy: " + (double)numCorrect / validationSet.size() * 100 + "%");

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

sample.label = Integer.parseInt(tokens[0]);

due to this statement, you get NumberFormatException because suppose you access t10 row which is not convertible to integer using interger.parseint it is not internally treated as a string

Add a comment
Know the answer?
Add Answer to:
I was running a CVS file using KNN(java) to find and calculate the shortest distance with...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)...

    Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming) import java.io.*; import java.net.*; public class WelcomeClient { public static void main(String[] args) throws IOException {    if (args.length != 2) { System.err.println( "Usage: java EchoClient <host name> <port number>"); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( Socket kkSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(kkSocket.getInputStream())); ) { BufferedReader...

  • I need help with adding comments to my code and I need a uml diagram for...

    I need help with adding comments to my code and I need a uml diagram for it. PLs help.... Zipcodeproject.java package zipcodesproject; import java.util.Scanner; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Zipcodesproject { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input=new Scanner(System.in); BufferedReader reader; int code; String state,town; ziplist listOFCodes=new ziplist(); try { reader = new BufferedReader(new FileReader("C:UsersJayDesktopzipcodes.txt")); String line = reader.readLine(); while (line != null) { code=Integer.parseInt(line); line =...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • can some one help me solve this and explain it please Input Format A line indicating...

    can some one help me solve this and explain it please Input Format A line indicating the size of the array the array on the next line Constraints n < 10000 Output Format One line printing the array in order input (given to you) One line printing the array, followed by its maximum value Sample Input 0 5 1 3 5 7 9 Sample Output 0 1 3 5 7 9 9 7 5 3 1 9 Contest ends in...

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • I need help with my IM (instant messaging) java program, I created the Server, Client, and...

    I need help with my IM (instant messaging) java program, I created the Server, Client, and Message class. I somehow can't get both the server and client to message to each other. I am at a roadblock. Here is the question below. Create an IM (instant messaging) java program so that client and server communicate via serialized objects (e.g. of type Message). Each Message object encapsulates the name of the sender and the response typed by the sender. You may...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private...

    import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private static final String OUTPUT_FILE = "crimes.txt"; public static void main(String[] args) { int totalCrimes = 0; // read all the rows from the csv file and add the total count in the totalCrimes variable try { Scanner fileScanner = new Scanner(new File(INPUT_FILE)); String line = fileScanner.nextLine(); // skip first line while (fileScanner.hasNext()) { String[] tokens = fileScanner.nextLine().split(","); if (tokens.length == 4) { totalCrimes +=...

  • Java programming How do i change this program to scan data from file and find the...

    Java programming How do i change this program to scan data from file and find the sum of the valid entry and count vaild and invalid entries The provided data file contains entries in the form ABCDE BB That is - a value ABCDE, followed by the base BB. Process this file, convert each to decimal (base 10) and determine the sum of the decimal (base 10) values. Reject any entry that is invalid. Report the sum of the values...

  • The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....

    The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { //Declare the private members variables. private int type1,type2; private String CostInTime[][], SVertex, DVertex; private List<String> listOfTheNodes; private Set<String> List; private List<Root> ListOfVisitedNode; private HashMap<String, Integer> minimalDistance; private HashMap<String, Integer> distOfVertices; private PriorityQueue<City> priorityQueue; // prove the definition...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT