学习6-4 实现线性回归中的梯度下降法时,在JupterNotebook中按照教程来完全没有问题。但是在pycharm中封装这个方法时:
def fit_gd(self, X_train, y_train, eta = 0.01, n_iters=1e4):
"""根据训练数据集X_train, y_train,使用梯度下降法训练Linear Regression模型"""
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
def J(theta, X_b, y):
try:
return np.sum((y - X_b.dot(theta)) ** 2) / len(y)
except:
return float('inf')
def dJ(theta, X_b, y):
res = np.empty(len(theta))
res[0] = np.sum(X_b.dot(theta) - y)
for i in range(1, len(theta)):
res[i] = (X_b.dot(theta) - y).dot(X_b[:, i])
return res * 2 / len(X_b)
def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1
'
qq_37887345 于 2019-09-19 19:38:16 发布
在实现线性回归的梯度下降时,遇到`TypeError: data type not understood`错误。问题出在numpy的ones()函数使用上,需明确指定shape参数,如`np.ones((1, 1))`。此外,当X_train为矩阵时,`x.reshape(-1, 1)`确保数据为列向量,避免潜在错误。" 129921722,10324361,重新推送耗用批次的入库与出库数据,"['数据库', '数据同步', '流程管理'] 
