代码来源
(https://github.com/MLEveryday/100-Days-Of-ML-Code.git)
说明:文章中的python代码大部分来自于github(少数是学习时测试添加),所附笔记为学习时注。
Day2 简单线性回归
基本步骤:
数据预处理–>通过训练集来训练简单线性回归模型–>预测结果–>可视化
学习笔记(含测试部分)
# Day2:Simple_Linear_Regression
# 2019.2.14
# coding=utf-8
# Data Preprocessing
# 1.引入所需要的库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 2.导入数据
dataset = pd.read_csv('C:/Users/Ymy/Desktop/100-Days-Of-ML-Code/datasets/studentscores.csv');
# X为导入dataset的第0列,Y为第1列
X = dataset.iloc[:,:1].values
Y = dataset.iloc[:,1].values
# 3.检查缺失数据(由于此数据无缺失值,此步骤省略)
# 4.划分数据集(测试集合占25%)
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 1/4, random_state = 0)
# Fitting Simple Linear Regression Model to the training set
# 1.使用sklearn.linear_model的LinearRegression类
from sklearn.linear_model import LinearRegression
# 2.创建LinearRegression类的对象regressor,并使用fit()方法
'''
fit方法:
def fit(self, X, y, sample_weight=None):
"""
Fit linear model.
Parameters(参数)
----------
X (训练数据): array-like or sparse matrix, shape (n_samples, n_features)
Training data
y (目标值): array_like, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : numpy array of shape [n_samples]
Individual weights for each sample
.. versionadded:: 0.17
parameter *sample_weight* support to LinearRegression.
Returns(返回值)
-------
self : returns an instance of self.
"""
'''
regressor = LinearRegression()
regressor = regressor.fit(X_train, Y_train)
# Predecting the Result
# 使用上一步的方法,预测测试集的结果
'''
predict方法:
def predict(self, X):
"""
Predict using the linear model
Parameters
----------
X : array_like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
C : array, shape (n_samples,)
Returns predicted values.
"""
'''
Y_pred = regressor.predict(X_test)
# Visualising the Training results(可视化训练集结果,18组数据)
# 1.绘制x,y的散点图,点的颜色为黄色
# matplotlib.pyplot的scatter方法(具体细节见底部链接)
'''
def scatter(
x, y, s=None, c=None, marker=None, cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
edgecolors=None, *, data=None, **kwargs)
"""
Parameters
----------
x, y : array_like, shape (n, ) The data positions.
s : scalar or array_like, shape (n, ), optional
c : color, sequence, or sequence of color, optional
"""
'''
plt.scatter(X_train , Y_train, color = 'yellow')
# 2.绘制训练集X与根据训练集方法所预测的'Y',颜色为黑色
# matplotlib.pyplot的plot方法(具体细节见底部链接)
plt.plot(X_train , regressor.predict(X_train), color ='black')
# 3.显示(此处如果显示,图中包含18个散点)
#plt.show()
# Visualizing the test results(可视化测试集结果)
#操作同上
plt.scatter(X_test , Y_test, color = 'red')
plt.plot(X_test , regressor.predict(X_test), color ='blue')
#此处显示,图中包含25个点,即全部数据
plt.show()
输出
p1:
p2(train):
p3(test):
注:按照学习部分的代码,运行输出结果为p1;根据p1可以看出,图中包含两组数据,为train和test两组数据集所绘制图像的叠加,而p2和p3就分别对应为train和test两组数据集单独绘制的图像。
资料参考:
sklearn.linear_model.LinearRegression:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
matplotlib.pyplot.scatter:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html
matplotlib.pyplot.plot:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib-pyplot-plot