我想用x[100,4]的样本和标签y来计算梯度下降.当我执行代码时,面对这个错误



我是python的初学者,当我想执行这段代码时,会遇到这个错误。有人能帮我吗?用于计算具有x[100,4]和y 样本的梯度下降


#Task 2
m,n = np.shape(x)
iteration = 100
k = 20
etha = 0.1
landa = 1
theta = np.zeros(n)
def train_classifier(theta, iteration, etha , k):
for i in range(0, iteration):
etha = etha / np.sqrt(iteration)
theta = theta - etha * (1 / k) * grad(theta, x, y)
return theta
def grad(theta, x, y):
xTranse = x.transpose()
cost = np.sum(logistic(x, theta) - y)
gradiant = np.dot(cost, xTranse) 
return gradiant
def logistic(x, theta):
pri = np.dot(x, theta)
hypo = 1 / (1 + np.exp(pri))
return hypo

j = train_classifier(theta, iteration, etha , k)
print(j)

<ipython-input-3-f3d8c56159d6> in train_classifier(theta, iteration, etha, k)
38     x1 = x[i:,]
39     etha = etha / np.sqrt(iteration)
---> 40     theta = theta - etha * (1 / k) * grad(theta, x, y)
41     return theta
42 def grad(theta, x, y):
ValueError: operands could not be broadcast together with shapes (4,) (4,100) 

这似乎有点奇怪。你有100个具有4种不同功能的样品吗?但只有4个标签?

这是加载样本和标签x,y 的代码

data = pd.read_csv('lab_iris_data.csv', header = None)
z = data.to_numpy()
x = z[:,0:3].astype(float)
labels = z[:,-1]
y = np.array([i == 'Iris-setosa' for i in labels])
i0 = np.where( y == True)[0]
i1 = np.where( y == False)[0]
y = y.astype(int)
x = np.c_[np.ones((x.shape[0])), x]
#plt.figure(figsize = (10,7))
#plt.grid()
#plt.xlabel('feature 1')
#plt.ylabel('feature 2')
#plt.scatter( x[i0,1], x[i0,2], x[i0,3])
#plt.scatter( x[i1,1], x[i1,2], x[i1,3])  

最新更新