简体   繁体   中英

TypeError: unsupported operand type(s) for -: 'float' and 'str'

I am new to Python and am stuck with what to do right now because I keep getting this error.I am trying to change the following equation like:

z = np.power(((float(X) * theta.T)-float(Y)), 2)

but I can't seem to get it to work.

My code:

# convert from data frames to numpy matrices
X = np.matrix(x.values)  
Y = np.matrix(y.values)  
theta = np.matrix(np.array([0,0]))
# cost functionstrong text
def computeCost(X, Y, theta):
    z = np.power(((X * theta.T)-Y), 2)
    return np.sum(z) / (2 * len(X))
print('computeCost(X, y, theta) = ' , computeCost(X, Y, theta))

the matrix is full of float numbers:

 X = [[ 1.      6.1101] [ 1.      5.5277] [ 1.      8.5186] ...

The error message:

TypeError: unsupported operand type(s) for -: 'float' and 'str'

I appreciate all the help I can get. Thanks a lot

do check datatypes of your dataframe

df.info()

if there's 'object' datatype, that's your string

you may want all datatypes in your dataframe as float, you can do it

df.astype('float')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM