首页 > 解决方案 > Python/机器学习 - 线性回归,TypeError:'list' 对象不可调用

问题描述

我目前正在构建一个 Python 应用程序,该应用程序根据用户输入的两个数组(分别为 x 轴和 y 轴)绘制图形。我可以很好地将结果绘制在图表本身上,但我正在努力创建一条线性回归线。

每当我尝试运行程序时,都会出现以下错误;TypeError:“列表”对象不可调用

这是有问题的代码 - 发生此问题的函数的名称称为 plotGraph。

有谁知道是什么原因造成的以及如何解决这个问题?

谢谢!

# importing pyplot to draw the graph including the line of linear regression
import matplotlib.pyplot as plt
# importing scipy to draw the line of Linear Regression
from scipy import stats
# needed for making the X and Y axis numpy arrays
import numpy

# boolean values
# these booleans will be referred to as global variables in functions so the value can be changed
xAxisAdded = False
yAxisAdded = False
menu = True

# new arrays for the x and Y axis
yearX = []
valueY = []

def addToXAxis():
    global xAxisAdded
    while xAxisAdded == False:
        monthCount = 1
        print("Adding values to the X axis (year) - the X axis can hold only 20 values")
        while monthCount <= 20:
            print(f"Please enter the value ")
            year = input(">")
            yearX.append(year)
            print(f"Added year {year}")
            monthCount += 1
        else:
            xAxisAdded = True
    else:
        print("X axis is now populated.\nIf you want to add new values, please clear the currently held values.")
        print("Press enter to return to the main menu.")
        enter = input("")

def clearXAxis(yearX):
    global xAxisAdded
    print("Now clearing all held values in the X axis.\nPlease wait...")
    yearX.clear()
    xAxisAdded = False
    print("Values in the X axis have been cleared. You can now add new values to the X axis.\nPress enter to return to the main menu")
    enter = input("")

def displayXAxis(yearX):
    print("Now displaying the values held in the X axis")
    print(yearX)
    print("\nPress enter to return to the main menu.")
    enter = input("")

def addtoYAxis():
    global yAxisAdded
    while yAxisAdded == False:
        monthCount = 1
        print("Adding values to the Y axis (value) - the Y axis can hold only 20 values")
        while monthCount <= 20:
            print(f"Please enter the value ")
            value = input(">")
            valueY.append(value)
            print(f"Added value {value}")
            monthCount += 1
        else:
            yAxisAdded = True
    else:
        print("Y axis is now populated.\nIf you want to add new values, please clear the currently held values.")
        print("Press enter to continue.")
        enter = input("")

def clearYAxis(valueY):
    global yAxisAdded
    print("Now clearing all held values in the Y axis.\nPlease wait...")
    valueY.clear()
    yAxisAdded = False
    print("Values in the Y axis have been cleared. You can now add new values to the Y axis.\nPress enter to return to the main menu")
    enter = input("")

def displayYAxis(valueY):
    print("Now displaying the values held in the Y axis")
    print(valueY)
    print("\nPress enter to return to the main menu")
    enter = input("")

def plotGraph(yearX, valueY):
    global xAxisAdded, yAxisAdded
    if xAxisAdded == True & yAxisAdded == True:
        print("Now drawing graph, please wait...")
        # key info for linear regression
        slope, intercept, rSquared, p, std_err = stats.linregress(yearX, valueY)
        drawX = slope * numpy.asarray(yearX) + intercept
        # run through each value from the X axis via the drawX function
        # this creates a list object (list) and calculates the length of each word in the tuple (map)
        newModel = list(map([drawX], yearX))
        # draw the scatter plot
        plt.scatter(yearX, valueY)
        # draws the line of linear regression
        plt.plot(yearX, newModel)
        # display
        plt.show()
    else:
        print("Error! Please ensure that both the X axis and Y axis have values before plotting a graph.")

while menu == True:
    print("""Welcome to the House Price Calculator!
Type in the value against a menu option you want to run!
1) Add values to the X axis (year)
2) Add values to the Y axis (value)
3) Display values in X axis (year)
4) Display values in Y axis (value)
5) Plot graph (using values in X and Y axis)
6) Clear values in the X axis (year)
7) Clear values in the Y axis (value)
q) Quit""")
    menuChoice = input(">")
    if menuChoice == '1':
        addToXAxis()
    elif menuChoice == '2':
        addtoYAxis()
    elif menuChoice == '3':
        displayXAxis(yearX)
    elif menuChoice == '4':
        displayYAxis(valueY)
    elif menuChoice == '5':
        plotGraph(yearX, valueY)
    elif menuChoice == '6':
        clearXAxis(yearX)
    elif menuChoice == '7':
        clearYAxis(valueY)
    elif menuChoice == 'q':
        print("Goodbye!")
        menu = False
    else:
        print("Error! Please try again!")

追溯:

Traceback (most recent call last):
  File "housePriceCalculator.py", line 125, in <module>
    plotGraph(yearX, valueY)
  File "housePriceCalculator.py", line 94, in plotGraph
    newModel = list(map([drawX], yearX))
TypeError: 'list' object is not callable

标签: pythonnumpymatplotlib

解决方案


推荐阅读