【发布时间】:2018-12-06 17:12:54
【问题描述】:
# Python code to demonstrate SQL to fetch data.
# importing the module
import sqlite3
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from scipy.stats import chisquare
# connect withe the myTable database
connection = sqlite3.connect(r"C:\Users\Aidan\Desktop\CEP_DB.db")
# cursor object
crsr = connection.cursor()
dog= crsr.execute("Select s, ei, ki FROM cep_db_lite1_vc WHERE s IN ('d')")
ans= crsr.fetchall()
dogData = np.array(ans)
FdogData= dogData[:, [1,2]]
x, y = FdogData[:,0], FdogData[:,1]
# Reshaping
x, y = x.reshape(-1,1), y.reshape(-1, 1)
# Linear Regression Object
lin_regression = LinearRegression()
# Fitting linear model to the data
lin_regression.fit(x,y)
# Get slope of fitted line
m = lin_regression.coef_
# Get y-Intercept of the Line
b = lin_regression.intercept_
# Get Predictions for original x values
# you can also get predictions for new data
predictions = lin_regression.predict(x)
chi= chisquare(predictions, y)
# following slope intercept form
print ("formula: y = {0}x + {1}".format(m, b))
print(chi)
# Plot the Original Model (Black) and Predictions (Blue)
plt.scatter(x, y, color='black')
plt.plot(x, predictions, color='blue',linewidth=3)
plt.show()
存储在数组中的数据:
[['d' '-72.70' '3.20']
['d' '-74.81' '']
['d' '-87.60' '5.50']
['d' '-91.38' '']
['d' '-71.80' '']
['d' '-73.10' '']
['d' '-81.20' '']
['d' '-81.40' '']
['d' '-75.70' '5.70']
['d' '-83.50' '5.10']
['d' '-73.90' '']
['d' '-82.60' '']
['d' '-77.30' '']
['d' '-85.10' '']
['d' '-79.70' '']
['d' '-78.70' '']
['d' '-77.90' '']
['d' '-76.80' '']
['d' '-83.80' '']
['d' '-83.90' '']
['d' '-82.00' '4.90']
['d' '-80.00' '4.80']]
错误输出/回溯
runfile('C:/Users/Aidan/.spyder-py3/temp.py', wdir='C:/Users/Aidan/.spyder-py3') Traceback(最近一次调用最后):
文件“”,第 1 行,在 runfile('C:/Users/Aidan/.spyder-py3/temp.py', wdir='C:/Users/Aidan/.spyder-py3')
文件 "C:\Users\Aidan\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 705 行,在运行文件中 execfile(文件名,命名空间)
文件 "C:\Users\Aidan\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 102 行,在 execfile 中 exec(编译(f.read(),文件名,'exec'),命名空间)
文件“C:/Users/Aidan/.spyder-py3/temp.py”,第 32 行,在 lin_regression.fit(x,y)
文件 "C:\Users\Aidan\Anaconda3\lib\site-packages\sklearn\linear_model\base.py", 第 489 行,合适 复制=self.copy_X, sample_weight=sample_weight)
文件 "C:\Users\Aidan\Anaconda3\lib\site-packages\sklearn\linear_model\base.py", 第 169 行,在 _preprocess_data 中 y = np.asarray(y, dtype=X.dtype)
文件 "C:\Users\Aidan\Anaconda3\lib\site-packages\numpy\core\numeric.py", 第 492 行,在数组中 返回数组(a, dtype, copy=False, order=order)
ValueError:无法将字符串转换为浮点数:
如何解决浮动错误?
【问题讨论】:
-
我在哪里写浮动?我可以浮动整个数组吗?
-
如果没有更多信息,我们只能猜测您收到 ValueError 的原因。失败的调用中使用的 x 和 y 的值是什么?
-
我将数组中的第二列和第三列设为 X 和 Y
标签: python python-3.x