Giter Club home page Giter Club logo

Comments (1)

YoungBooker avatar YoungBooker commented on May 27, 2024

`from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
import matplotlib.pyplot as plt
import numpy as np
import seaborn

def PolynomialRegression(degree=2,**kwargs):
#建立多项式回归模型
return make_pipeline(PolynomialFeatures(degree),
LinearRegression(**kwargs))

def make_data(N,err=1.0,rseed=1):
#随机抽样数据
rng=np.random.RandomState(rseed)
X=rng.rand(N,1)**2
y=10-1./(X.ravel()+0.1)
if err > 0:
y+=err*rng.randn(N)
return X,y

X,y=make_data(40)
param_grid = {'polynomialfeatures__degree': np.arange(21),
'linearregression__fit_intercept': [True, False]}

#网格搜索
grid = GridSearchCV(PolynomialRegression(), param_grid, cv=7)

#调用方法fit(),并同时记录每个点的得分
grid.fit(X,y)

#打印最优参数
print(grid.best_params_)

#设置图样格式
seaborn.set()
#用最优参数的模型拟合数据
model=grid.best_estimator_
#画出随机数据的散点图
plt.scatter(X.ravel(),y)

lim=plt.axis()
X_test=np.linspace(-0.1,1.1,500)[:,None]
#predict是训练后返回预测结果,是标签值
y_test=model.fit(X,y).predict(X_test)
plt.plot(X_test.ravel(),y_test)
plt.axis(lim)`

from pythondatasciencehandbook.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.