So I'm trying to use linear regression to show a trendline when entering a set of data points. I'm using Tkinter to get an input for the data, and then converting them to float to put them in a list. I get this error code when I run the program though.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:/Users/NIBO9901/PycharmProjects/Matteuppgift/Trendlinje/Input.py", line 78, in plot
m, c = np.linalg.lstsq(a, y)[0]
File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 1889, in lstsq
nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
ValueError: math domain error
And the code that it's refering to is here:
xList = []
yList = []
x = np.array(xList)
y = np.array(yList)
if 0 < len(inpX0.get()):
xList.append(float(inpX0.get()))
if 0 < len(inpX1.get()):
xList.append(float(inpX1.get()))
if 0 < len(inpY0.get()):
yList.append(float(inpY0.get()))
if 0 < len(inpY1.get()):
yList.append(float(inpY1.get()))
a = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(a, y)[0]
plt.plot(x, y, 'o', label='Data', markersize=10)
plt.plot(x, m*x + c, 'r', label='Trendlinje')
plt.legend()
plt.show()
inpX/Y are the Tkinter entries.
numpy arrays are static structures. You first have to populate your list and then convert it to a numpy array. After that, modifications to the list will not have an effect on the numpy array anymore.
So what you want to do is probably:
xList = []
yList = []
if 0 < len(inpX0.get()):
xList.append(float(inpX0.get()))
if 0 < len(inpX1.get()):
xList.append(float(inpX1.get()))
if 0 < len(inpY0.get()):
yList.append(float(inpY0.get()))
if 0 < len(inpY1.get()):
yList.append(float(inpY1.get()))
a = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(a, y)[0]
# the lists are complete, now convert them to numpy arrays
x = np.array(xList)
y = np.array(yList)
plt.plot(x, y, 'o', label='Data', markersize=10)
plt.plot(x, m*x + c, 'r', label='Trendlinje')
plt.legend()
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With