运行回归代码遇AttributeError:sklearn无linear_model属性
AttributeError: module 'sklearn' has no attribute 'linear_model'
我来帮你分析下这个问题——你遇到的这个错误本质是scikit-learn的子模块需要显式导入,不能只靠顶层的import sklearn就直接访问深层子模块。
问题原因
你的代码里只写了import sklearn,但linear_model是sklearn的一个子模块,默认不会自动导入到顶层命名空间里,所以当你尝试用sklearn.linear_model.LinearRegression()时,Python找不到这个属性。
修复方案
你有两种简单的修复方式:
方式1:显式导入linear_model子模块
在代码开头的导入部分添加这一行:
from sklearn import linear_model
然后把创建模型的代码改成:
lin_reg_model = linear_model.LinearRegression()
方式2:直接导入LinearRegression类
如果不想写长长的模块路径,可以直接导入目标类:
from sklearn.linear_model import LinearRegression
然后创建模型的代码简化为:
lin_reg_model = LinearRegression()
额外提示
另外,你的代码里还有一个过时的导入:
import sklearn.cross_validation
在新版本的scikit-learn中,cross_validation模块已经被迁移到model_selection下了,如果后续运行遇到相关错误,记得改成:
from sklearn import model_selection
修复后的完整代码示例
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import model_selection # 替换过时的cross_validation from sklearn.linear_model import LinearRegression # 导入需要的模型类 # Load the data oecd_bli = pd.read_csv("C:/Users/Excel/Desktop/Briefcase/PDFs/ALL PYTHON & R CODE SAMPLES/Hands-On Machine_Learning_with_Scikit_Learn_and_Tensorflow/GDP Per Capita/oecd_bli.csv", thousands=',') gdp_per_capita = pd.read_csv("C:/Users/Excel/Desktop/Briefcase/PDFs/ALL PYTHON & R CODE SAMPLES/Hands-On Machine_Learning_with_Scikit_Learn_and_Tensorflow/GDP Per Capita/gdp_per_capita.csv",thousands=',') # view first 10 rows of data frame oecd_bli[:10] gdp_per_capita[:10] country_stats = pd.merge(oecd_bli, gdp_per_capita, left_index=True, right_index=True) country_stats[:10] X = np.c_[country_stats["GDP"]] Y = np.c_[country_stats["VALUE"]] print(X) print(Y) # Visualize the data country_stats.plot(kind='scatter', x="GDP", y='VALUE') plt.show() # Select a linear model lin_reg_model = LinearRegression() # Train the model lin_reg_model.fit(X, Y) # Make a prediction for Cyprus X_new = [[22587]] # Cyprus' GDP per capita print(lin_reg_model.predict(X_new))
内容的提问来源于stack exchange,提问作者ASH
相关产品推荐
相关产品推荐

