分享

R|ML_code-线性回归(2)

 生信补给站 2020-05-14

回归分析是一种预测性的建模技术,它研究的是因变量(目标)和自变量(预测器)之间的关系。本文简单的介绍一下简单线性回归。

Simple Linear Regression

Data Preprocessing

1 读入数据集

# Importing the dataset dataset <- read.csv('studentscores.csv') #时间和得分之间的关系  Hours Scores 1   2.5     21 2   5.1     47 3   3.2     27 4   8.5     75 5   3.5     30 6   1.5     20 plot(dataset$Hours,dataset$Scores) #

如图可见符合线性回归模型,根据训练集数据进行回归函数分析,并对测试数据进行预测。

2 数据预处理

首先按照上次分享的进行数据预处理  

R|ML_code-入门(1)

3 训练集和测试集

将数据按照4:1拆分,每一组分别包含自变量和因变量

# Splitting the dataset into the Training set and Test set # install.packages('caTools') library(caTools) set.seed(123) split = sample.split(dataset$Scores, SplitRatio = 1/4) training_set <- subset(dataset, split == TRUE) test_set <- subset(dataset, split == FALSE) # Feature Scaling # training_set <- scale(training_set) # test_set <- scale(test_set)

4 模型拟合及预测

通过训练集进行模型拟合得到曲线,然后将测试集的X_test带入曲线中,得到预测结果y_pred,最后将预测结果y_pred与测试集中的y_test进行比较,确定预测是否准确。

# Fitting Simple Linear Regression to the Training set regressor = lm(formula = Scores ~ Hours,               data = training_set) # Predicting the results y_pred <- predict(regressor, newdata = test_set)

5 结果可视化

# Visualising the Training  results library(ggplot2) ggplot() + geom_point(aes(x = training_set$Hours, y = training_set$Scores), colour = 'red') + geom_line(aes(x = training_set$Hours, y = predict(regressor, newdata = training_set)), colour = 'blue') + ggtitle('Scores vs Hours (Training set)') + xlab('Hours') + ylab('Scores') # Visualising the Test  results library(ggplot2) ggplot() + geom_point(aes(x = test_set$Hours, y = test_set$Scores), colour = 'red') + geom_line(aes(x = training_set$Hours, y = predict(regressor, newdata = training_set)), colour = 'blue') + ggtitle('Scores vs Hours (Test set)') + xlab('Hours') + ylab('Scores')

参考链接:

爆红GITHUB的百日入门机器学习项目

https://github.com/Avik-Jain/100-Days-Of-ML-Code/blob/master/Code/Day2_Simple_Linear_Regression.md

简单的线性回归就到这,下次多元线性回归。。。。。。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多