Python 类型错误:';numpy.float64';对象不适用于ML模型
我如何避免在突出显示的行上出现错误,它一直在给我关于float64类型不可编辑的错误。本质上,我试图在第一个函数中计算SGD的成本,然后在第二个函数中计算SGDPython 类型错误:';numpy.float64';对象不适用于ML模型,python,types,floating-point,Python,Types,Floating Point,我如何避免在突出显示的行上出现错误,它一直在给我关于float64类型不可编辑的错误。本质上,我试图在第一个函数中计算SGD的成本,然后在第二个函数中计算SGD def calculate_cost_gradient(W, X_batch, Y_batch): # if only one example is passed (eg. in case of SGD) if type(Y_batch) == np.float64: Y_batch = np.array
def calculate_cost_gradient(W, X_batch, Y_batch):
# if only one example is passed (eg. in case of SGD)
if type(Y_batch) == np.float64:
Y_batch = np.array([Y_batch])
X_batch = np.array([X_batch]) # gives multidimensional array
distance = 1 - (Y_batch * np.dot(X_batch, W))
dw = np.zeros(len(W))
######## Error is here ########
for ind, d in enumerate(distance):
if max(0, d) == 0:
di = W
else:
di = W - (regularization_strength * Y_batch[ind] * X_batch[ind])
dw += di
dw = dw/len(Y_batch) # average
return dw
def sgd(features, outputs):
max_epochs = 5000
weights = np.zeros(features.shape[1])
nth = 0
prev_cost = float("inf")
cost_threshold = 0.01 # in percent
# stochastic gradient descent
for epoch in range(1, max_epochs):
# shuffle to prevent repeating update cycles
X, Y = shuffle(features, outputs)
for ind, x in enumerate(X):
ascent = calculate_cost_gradient(weights, x, Y[ind])
weights = weights - (learning_rate * ascent)
# convergence check on 2^nth epoch
if epoch == 2 ** nth or epoch == max_epochs - 1:
cost = compute_cost(weights, features, outputs)
print("Epoch is:{} and Cost is: {}".format(epoch, cost))
# stoppage criterion
if abs(prev_cost - cost) < cost_threshold * prev_cost:
return weights
prev_cost = cost
nth += 1
return weights
def计算成本梯度(W、X、Y批次):
#如果只通过了一个示例(如SGD)
如果类型(Y_批次)=np.64:
Y\u batch=np.array([Y\u batch])
X_batch=np.数组([X_batch])#给出多维数组
距离=1-(Y_批次*np.点(X_批次,W))
dw=np.零(len(W))
########错误就在这里
对于ind,枚举中的d(距离):
如果最大值(0,d)=0:
di=W
其他:
di=W-(正则化强度*Y\u批次[ind]*X\u批次[ind])
dw+=di
dw=dw/len(Y#U批次)#平均值
返回数据仓库
def sgd(功能、输出):
最大纪元=5000
权重=np.0(features.shape[1])
n=0
上一成本=浮动(“inf”)
成本阈值=0.01(百分比)
#随机梯度下降
对于范围内的历元(1,最大历元):
#洗牌以防止重复更新周期
十、 Y=随机播放(功能、输出)
对于ind,枚举中的x(x):
上升=计算成本梯度(权重,x,Y[ind])
权重=权重-(学习率*上升)
#第2^n历元的收敛性检验
如果历元==2**n或历元==max\u历元-1:
成本=计算成本(权重、特征、输出)
打印(“历元为:{},成本为:{}”。格式(历元,成本))
#停工标准
如果abs(上一成本-成本)<成本阈值*上一成本:
回程重量
上一成本=成本
n+n=1
回程重量
距离很可能是一个整数,代码应该是:
for ind, d in enumerate(range(distance)):