m0_72041809 2022-07-06 20:23 采纳率: 50%

# python数据类型报错

###### 问题遇到的现象和发生背景

python 写线性回归代码时遇到变量类型报错的问题

###### 问题相关代码，请勿粘贴截图
``````def train(self,alpha,num_iterations = 500):

return self.theta,cost_history

cost_history = []
for x in range(num_iterations):
cost_history.append(self.cost_function(self.data,self.labels))
return cost_history

num_examples = data.shape[0]
prediction = LinearRegression.hypothesis(self.data,self.theta)
delta = prediction - self.labels
theta = self.theta
theta = theta - alpha*(1/num_examples)*(np.dot(delta.T,self.data)).T
self.theta = theta

def cost_function(self,data,labels):
self.m = len(labels)
delta = LinearRegression.hypothesis(data,self.theta) - labels
cost = (1/2)*np.dot(delta.T,delta)/self.m
return cost[0][0]

def hypothesis(data,theta):
predictions = np.dot(data,theta)
return predictions

x_train =rescombine
y_train = labels

num_iterations = 500
learning_rate = 0.01

linear_regression = LinearRegression(x_train, y_train)

(theta, cost_history) = LinearRegression.train(learning_rate, num_iterations)##此处有问题

print(theta, cost_history)
print('开始损失',cost_history[0])
print('结束损失',cost_history[-1])
``````
###### 运行结果及报错内容

'float' object has no attribute 'gradient_descent'
File "C:\Users\Xpc\Desktop\LinearRegression\linear_regression.py", line 299, in train
File "C:\Users\Xpc\Desktop\LinearRegression\linear_regression.py", line 340, in
(theta, cost_history) = LinearRegression.train(learning_rate, num_iterations)

• 写回答

#### 3条回答默认 最新

• 天际的海浪 2022-07-06 20:42
关注

你调用train()方法的方式不对
要用LinearRegression类的实例对象 linear_regression 调用train()方法
不是用LinearRegression类本身调用train()方法,

``````(theta, cost_history) = LinearRegression.train(learning_rate, num_iterations)##此处有问题
``````

改成

``````(theta, cost_history) = linear_regression.train(learning_rate, num_iterations)##此处有问题
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论 编辑记录

• 系统已结题 7月15日
• 已采纳回答 7月7日
• 创建了问题 7月6日

#### 悬赏问题

• ¥15 爬取网页信息并附加完整代码
• ¥15 CST2023安装报错