numpy - how can the string convert to int in python? -
numpy - how can the string convert to int in python? -
in machine learning in action chapter 2, 1 illustration reads records file, each line like:
124 110 223 largedoses
(forget actual meaning)
one function in knn.py
is:
def file2matrix(filename): fr = open(filename) numberoflines = len(fr.readlines()) returnmat = zeros((numberoflines,3)) classlabelvector = [] fr = open(filename) index = 0 line in fr.readlines(): line = line.strip() listfromline = line.split('\t') returnmat[index,:] = listfromline[0:3] classlabelvector.append(int(listfromline[-1])) index += 1 homecoming returnmat,classlabelvector
the problem listfromline[-1]
string ('largedoses'
, etc.), how can convert int
?
in book, says numpy
can handle this.
(from book : you have explicitly tell interpreter you’d integer version of lastly item in list, or give string version. usually, you’d have this, numpy takes care of details you.) however,
valueerror: invalid literal int() base of operations 10: 'largedoses'
occurs for
import knn knn.file2matrix('dataset.txt')
btw, book's chinese version different english language version.
string (indeed) cannot convert int, neither in python, nor in other environment,
however,
the solution is
put machine learning (indeed) in actionin case knn
-input training / cross-validation records ( a.k.a. observations, examples )
do conform convention of [ 3x feature, 1x label]
use:
classlabelvector.append( listfromline[-1] ) # .append label, not int()
python numpy
Comments
Post a Comment