m0_72041809 2022-07-06 20:23 采纳率: 50%
浏览 46
已结题

python数据类型报错

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

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

问题相关代码,请勿粘贴截图
def train(self,alpha,num_iterations = 500):
       
        cost_history = self.gradient_descent(alpha,num_iterations)##此处有问题
        return self.theta,cost_history
        
    def gradient_descent(self,alpha,num_iterations):
        cost_history = []
        for x in range(num_iterations):
            self.gradient_step(alpha)
            cost_history.append(self.cost_function(self.data,self.labels))
        return cost_history
        
        
    def gradient_step(self,alpha):    
        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])
运行结果及报错内容

发生异常: AttributeError
'float' object has no attribute 'gradient_descent'
File "C:\Users\Xpc\Desktop\LinearRegression\linear_regression.py", line 299, in train
cost_history = self.gradient_descent(alpha,num_iterations)
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
    关注

    你 self.gradient_descent(alpha,num_iterations) 中 self是float浮点数类型,不可能有gradient_descent方法吧
    你调用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)##此处有问题
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵