现有数据集Advertising.csv。数据集包含了200个不同市场的产品销售额,每个销售额对应3种广告媒体投入成本,分别是:TV, radio, 和 newspaper。如果我们能分析出广告媒体投入与销售额之间的关系,我们就可以更好地分配广告开支并且使销售额最大化。
现需要进行如下实验:
1、使用pandas库读取数据集,得到相应矩阵。使用matplotlib库画出:TV、Radio、Newspaper与产品销售额的数据散点图。
具体要求:
- 结果为一张图,TV, radio, 和 newspaper需要用不同形状的点表示。
- 图的X轴为广告花费、Y轴为销售额的值。
- 需要画出虚线形式的网格参考线。
def graph1( data ):
TV = data.TV
Radio = data.Radio
Newspaper = data.Newspaper
Sales = data.Sales
plt.scatter(TV, Sales, c='r',marker='o',label='TV')
plt.scatter(Radio, Sales, c='b', marker='x', label='Radio')
plt.scatter(Newspaper, Sales, c='y', marker='d', label='Newspaper')
plt.legend()
plt.ylabel("销售额",fontproperties=zhfont1)
plt.xlabel('广告花费',fontproperties=zhfont1)
plt.grid(linestyle='-.')
plt.savefig('D://Ml_lab_result/ProblemA_1.png')
plt.show()
2、 再次使用matplotlib库
分别
画出:TV与产品销售额、 Radio与产品销售额、Newspaper与产品销售额的数据散点图。
具体要求:
- 结果为三张子图组成的一个大图,分为三行。从上到下的顺序依次为:TV与产品销售额、 Radio与产品销售额、Newspaper与产品销售额的数据散点图。
- 图的X轴为广告花费、Y轴为销售额的值。
- 需要画出虚线形式的网格参考线。
def graph2(data):
TV = data.TV
Radio = data.Radio
Newspaper = data.Newspaper
Sales = data.Sales
plt.ylabel("销售额", fontproperties=zhfont1)
plt.figure()
plt.subplot(311)
plt.scatter(TV, Sales, c='r',marker='o')
plt.grid(linestyle='-.')
plt.subplot(312)
plt.scatter(Radio, Sales, c='b', marker='x')
plt.grid(linestyle='-.')
plt.subplot(313)
plt.scatter(Newspaper, Sales, c='y', marker='d')
plt.xlabel('广告花费', fontproperties=zhfont1)
plt.grid(linestyle='-.')
plt.savefig('D://Ml_lab_result/ProblemA_2.png')
plt.show()
从图表可看出Newspaper的投入与产品销售额最无关系。
3、
先对数据进行标准化后
,建立线性回归中的多项式拟合模型,分别采用多项式的次数为
1-9
进行训练。最后根据预测结果与真实结果绘图。
具体要求:
- 测试集取20%,训练集取80%。因为数据特征有三个(TV,Radio,NewsPaper),无法绘制特征与预测结果的二维图形。因此X轴换为测试样本下标,Y轴为产品销售额。
- 分别画出9个图,在图中使用绿色线条代表模型针对测试集得出的预测销售额,使用红色线条代表测试集对应的实际产品销售额。图的标题表明线性模型多项式次数。
def mlr(data):
X = data[['TV','Radio','Newspaper']]
y = data['Sales']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,random_state=1)
for degree in range(1,10) :
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
plt.grid()
plt.plot(range(len(y_pred)),y_pred, c='g',label="predict")
plt.plot(range(len(y_pred)),y_test, c='r', label="true")
plt.title("degree %d" % degree)
plt.legend()
path_img = 'D://Ml_lab_result/degree_%d.png' % degree
plt.savefig(path_img)
plt.show()
版权声明:本文为qq_38054219原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。