gpt4 book ai didi

python - 尝试使用 sk learn 绘制线性回归模型时遇到模糊的 RuntimeWarning

转载 作者:行者123 更新时间:2023-11-30 09:47:54 32 4
gpt4 key购买 nike

import pandas
import math
from csv import reader
import sys
import numpy as np
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
import scipy.optimize as opt
import warnings
from sklearn import model_selection
from sklearn import linear_model


def fxn():
warnings.warn("Runtime Warning",RuntimeWarning)

with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
def costcomp(X,y,theta):
inner=np.power(((X*theta.T)-y),2)
return np.sum(inner)/(2*len(X))


def gradient(theta,X,y,lr,itr):
temp=np.matrix(np.zeros(theta.shape))
parameters=int(theta.ravel().shape[1])
cost=np.zeros(itr)
for i in range(itr):
err=(X*theta.T)-y
for j in range(parameters):
tem=np.multiply(err,X[:,j])
temp[0,j]=theta[0,j]-((lr/len(X))*np.sum(tem))
theta=temp
cost[i]=costcomp(X,y,theta)

return theta,cost


dataset = pandas.read_csv("PYTHONFINAL.csv",names=['Month','Year','Day','Time','SpeedLimit','Age','Accidents'])
dataset = (dataset- dataset.mean()) / dataset.std()
dataset.insert(0, 'Ones', 1)

cols=dataset.shape[1]
X=dataset.iloc[:,0:cols-1]
y=dataset.iloc[:,cols-1:cols]
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0,0,0,0,0,0]))
X_train, X_validation, y_train, y_validation = model_selection.train_test_split(X, y, test_size=0.20, random_state=7)
print(costcomp(X_train,y_train,theta))
learningrate=0.01
iterations=2000
grad,costf=gradient(theta,X_train,y_train,learningrate,iterations)
print(grad)
print(costcomp(X_train,y_train,grad))
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iterations),costf, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')

# **PROBLEM STARTS HERE**

model = linear_model.LinearRegression()
model.fit(X, y)
x = np.array(X[:, 1].A1)
f = model.predict(X).flatten()

plt.show()


x = np.linspace(dataset.Month.min(), dataset.Month.max(), 100)
f = grad[0, 0] + (grad[0, 1] * x)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(dataset.Month, dataset.Accidents, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Month')
ax.set_ylabel('Accidents')
ax.set_title('Predicted Accidents vs. Month')

错误:

Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/linalg/basic.py", line 1226
warnings.warn(mesg, RuntimeWarning)
RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.

问题:

我一直想绘制一个图表来看看线性回归模型构建是否有效。因此,我想要一个我构建的模型和用于该程序的原始数据集的回归线图。head(20 )我使用的数据集的值在所附图像中提供。

Dataset for the problem

最佳答案

您可以使用此代码来抑制这些特殊警告。

import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")

关于python - 尝试使用 sk learn 绘制线性回归模型时遇到模糊的 RuntimeWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49918108/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com