ASH
ASH

Reputation: 20342

Trying to run regression code. Getting error about 'linear_model'

I am trying to run this regression code.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
import sklearn.cross_validation

# 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 = sklearn.linear_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))

I get this error.

AttributeError: module 'sklearn' has no attribute 'linear_model'

I'm not sure what's going on. I am trying to learn about this from an example that I saw in a book.

Upvotes: 1

Views: 529

Answers (3)

PritamJ
PritamJ

Reputation: 375

#import package, call the class   
from sklearn.linear_model import LinearRegression

#build the model(create a regression object)
model = LinearRegression()  

#fit the model
model.fit(x,y)

Upvotes: 1

akshat
akshat

Reputation: 1217

Python does not automatically import all the subpackages. When I tried to explicitly import, linear_module, it works:

from sklearn import linear_model

Upvotes: 0

ansvver
ansvver

Reputation: 317

linear_model is a subpackage of sklearn. It wont work if you only imported via: import sklearn. Try import sklearn.linear_model instead.

Upvotes: 0

Related Questions