python 代码中不支持的操作数类型错误
Unsupported operand type error in python code
所以当我 运行 下面的代码时:
from pylab import plt
import numpy as np
from pandas import DataFrame
from scipy.spatial.distance import pdist, squareform
z = open( 'WGTutorial/ZoneA.dat','r' ).readlines()
z = [ i.strip().split() for i in z[10:] ]
z = np.array( z, dtype=np.float )
z = DataFrame( z, columns=['x','y','thk','por','perm','lperm','lpermp','lpermr'] )
fig, ax = plt.subplots()
ax.scatter( z.x, z.y, c=z.por, cmap='gray' )
ax.set_aspect(1)
plt.xlim(-1500,22000)
plt.ylim(-1500,17500)
plt.xlabel('Easting [m]')
plt.ylabel('Northing [m]')
plt.title('Porosity %') ;
def SVh( P, h, bw ):
'''
Experimental semivariogram for a single lag
'''
pd = squareform( pdist( P[:,:2] ) )
N = pd.shape[0]
Z = list()
for i in range(N):
for j in range(i+1,N):
if( pd[i,j] >= h-bw )and( pd[i,j] <= h+bw ):
Z.append( ( P[i,2] - P[j,2] )**2.0 )
return np.sum( Z ) / ( 2.0 * len( Z ) )
def SV( P, hs, bw ):
'''
Experimental variogram for a collection of lags
'''
sv = list()
for h in hs:
sv.append( SVh( P, h, bw ) )
sv = [ [ hs[i], sv[i] ] for i in range( len( hs ) ) if sv[i] > 0 ]
return np.array( sv ).T
def C( P, h, bw ):
'''
Calculate the sill
'''
c0 = np.var( P[:,2] )
if h == 0:
return c0
return c0 - SVh( P, h, bw )
# part of our data set recording porosity
P = np.array( z[['x','y','por']] )
# bandwidth, plus or minus 250 meters
bw = 500
# lags in 500 meter increments from zero to 10,000
hs = np.arange(0,10500,bw)
sv = SV( P, hs, bw )
plt.plot( sv[0], sv[1], '.-' )
plt.xlabel('Lag [m]')
plt.ylabel('Semivariance')
plt.title('Sample Semivariogram') ;
#plt.savefig('sample_semivariogram.png',fmt='png',dpi=200)
def opt( fct, x, y, C0, parameterRange=None, meshSize=1000 ):
if parameterRange == None:
parameterRange = [ x[1], x[-1] ]
mse = np.zeros( meshSize )
a = np.linspace( parameterRange[0], parameterRange[1], meshSize )
type(y)
type(x)
type(a)
type(C0)
for i in range( meshSize ):
mse[i] = np.mean( ( y - fct( x, a[i], C0 ) )**2.0 )
return a[ mse.argmin() ]
def spherical( h, a, C0 ):
'''
Spherical model of the semivariogram
'''
# if h is a single digit
if type(h) == np.float64:
# calculate the spherical function
if h <= a:
return C0*( 1.5*h/a - 0.5*(h/a)**3.0 )
else:
return C0
# if h is an iterable
else:
# calcualte the spherical function for all elements
a = np.ones( h.size ) * a
C0 = np.ones( h.size ) * C0
return map( spherical, h, a, C0 )
def cvmodel( P, model, hs, bw ):
'''
Input: (P) ndarray, data
(model) modeling function
- spherical
- exponential
- gaussian
(hs) distances
(bw) bandwidth
Output: (covfct) function modeling the covariance
'''
# calculate the semivariogram
sv = SV( P, hs, bw )
# calculate the sill
C0 = C( P, hs[0], bw )
# calculate the optimal parameters
param = opt( model, sv[0], sv[1], C0 )
# return a covariance function
covfct = lambda h, a=param: C0 - model( h, a, C0 )
return covfct
sp = cvmodel( P, model=spherical, hs=np.arange(0,10500,500), bw=500 )
plt.plot( sv[0], sv[1], '.-' )
plt.plot( sv[0], sp( sv[0] ) ) ;
plt.title('Spherical Model')
plt.ylabel('Semivariance')
plt.xlabel('Lag [m]')
#plt.savefig('semivariogram_model.png',fmt='png',dpi=200)
我得到的错误是这样的;
File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 118, in cvmodel
param = opt( model, sv[0], sv[1], C0 )
File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 81, in opt
mse[i] = np.mean( ( y - fct( x, a[i], C0 ) )**2.0 )
TypeError: unsupported operand type(s) for -: 'float' and 'map'
我几天前迁移到 python,但我很难修复它。
哪位好心人可以帮帮我
错误消息中描述了问题:在那行代码中,y 是一个 float; fct 表达式的计算结果为数据类型 map。您不能从浮点数中减去地图。
当我跟踪你的代码时,fct 是一个预定义函数 spherical。 return 类型是什么?
替换
return map( spherical, h, a, C0 )
与:
return spherical(h, a, C0 )
已修复。我使用列表(地图(球形,h,a,c0))。 python3 映射函数 returns 是一个迭代器而不是直接列表。
所以当我 运行 下面的代码时:
from pylab import plt
import numpy as np
from pandas import DataFrame
from scipy.spatial.distance import pdist, squareform
z = open( 'WGTutorial/ZoneA.dat','r' ).readlines()
z = [ i.strip().split() for i in z[10:] ]
z = np.array( z, dtype=np.float )
z = DataFrame( z, columns=['x','y','thk','por','perm','lperm','lpermp','lpermr'] )
fig, ax = plt.subplots()
ax.scatter( z.x, z.y, c=z.por, cmap='gray' )
ax.set_aspect(1)
plt.xlim(-1500,22000)
plt.ylim(-1500,17500)
plt.xlabel('Easting [m]')
plt.ylabel('Northing [m]')
plt.title('Porosity %') ;
def SVh( P, h, bw ):
'''
Experimental semivariogram for a single lag
'''
pd = squareform( pdist( P[:,:2] ) )
N = pd.shape[0]
Z = list()
for i in range(N):
for j in range(i+1,N):
if( pd[i,j] >= h-bw )and( pd[i,j] <= h+bw ):
Z.append( ( P[i,2] - P[j,2] )**2.0 )
return np.sum( Z ) / ( 2.0 * len( Z ) )
def SV( P, hs, bw ):
'''
Experimental variogram for a collection of lags
'''
sv = list()
for h in hs:
sv.append( SVh( P, h, bw ) )
sv = [ [ hs[i], sv[i] ] for i in range( len( hs ) ) if sv[i] > 0 ]
return np.array( sv ).T
def C( P, h, bw ):
'''
Calculate the sill
'''
c0 = np.var( P[:,2] )
if h == 0:
return c0
return c0 - SVh( P, h, bw )
# part of our data set recording porosity
P = np.array( z[['x','y','por']] )
# bandwidth, plus or minus 250 meters
bw = 500
# lags in 500 meter increments from zero to 10,000
hs = np.arange(0,10500,bw)
sv = SV( P, hs, bw )
plt.plot( sv[0], sv[1], '.-' )
plt.xlabel('Lag [m]')
plt.ylabel('Semivariance')
plt.title('Sample Semivariogram') ;
#plt.savefig('sample_semivariogram.png',fmt='png',dpi=200)
def opt( fct, x, y, C0, parameterRange=None, meshSize=1000 ):
if parameterRange == None:
parameterRange = [ x[1], x[-1] ]
mse = np.zeros( meshSize )
a = np.linspace( parameterRange[0], parameterRange[1], meshSize )
type(y)
type(x)
type(a)
type(C0)
for i in range( meshSize ):
mse[i] = np.mean( ( y - fct( x, a[i], C0 ) )**2.0 )
return a[ mse.argmin() ]
def spherical( h, a, C0 ):
'''
Spherical model of the semivariogram
'''
# if h is a single digit
if type(h) == np.float64:
# calculate the spherical function
if h <= a:
return C0*( 1.5*h/a - 0.5*(h/a)**3.0 )
else:
return C0
# if h is an iterable
else:
# calcualte the spherical function for all elements
a = np.ones( h.size ) * a
C0 = np.ones( h.size ) * C0
return map( spherical, h, a, C0 )
def cvmodel( P, model, hs, bw ):
'''
Input: (P) ndarray, data
(model) modeling function
- spherical
- exponential
- gaussian
(hs) distances
(bw) bandwidth
Output: (covfct) function modeling the covariance
'''
# calculate the semivariogram
sv = SV( P, hs, bw )
# calculate the sill
C0 = C( P, hs[0], bw )
# calculate the optimal parameters
param = opt( model, sv[0], sv[1], C0 )
# return a covariance function
covfct = lambda h, a=param: C0 - model( h, a, C0 )
return covfct
sp = cvmodel( P, model=spherical, hs=np.arange(0,10500,500), bw=500 )
plt.plot( sv[0], sv[1], '.-' )
plt.plot( sv[0], sp( sv[0] ) ) ;
plt.title('Spherical Model')
plt.ylabel('Semivariance')
plt.xlabel('Lag [m]')
#plt.savefig('semivariogram_model.png',fmt='png',dpi=200)
我得到的错误是这样的;
File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 118, in cvmodel
param = opt( model, sv[0], sv[1], C0 )
File "C:/Users/PANATEC/Documents/Python Scripts/GlacMIK/Kriging.py", line 81, in opt
mse[i] = np.mean( ( y - fct( x, a[i], C0 ) )**2.0 )
TypeError: unsupported operand type(s) for -: 'float' and 'map'
我几天前迁移到 python,但我很难修复它。
哪位好心人可以帮帮我
错误消息中描述了问题:在那行代码中,y 是一个 float; fct 表达式的计算结果为数据类型 map。您不能从浮点数中减去地图。
当我跟踪你的代码时,fct 是一个预定义函数 spherical。 return 类型是什么?
替换
return map( spherical, h, a, C0 )
与:
return spherical(h, a, C0 )
已修复。我使用列表(地图(球形,h,a,c0))。 python3 映射函数 returns 是一个迭代器而不是直接列表。