import pandas as pd
#df=pd.read_csv('data_singlevar.txt',sep=',',header=None)
f=open('F:/python/4python机器学习经典案例/Python-Machine-Learning-Cookbook-master/Chapter01/data_singlevar.txt')
df=pd.read_csv(f,sep=',',header=None)
X=df.iloc[:,0].values
y=df.iloc[:,1].values
num_training=int(0.8*len(X))#80%的个数
num_test=len(X)-num_training#剩下的个数
#训练数据
X_train=X[:num_training].reshape((num_training,1))
y_train=y[:num_training]
#测试数据
X_test=X[num_training:].reshape((num_test,1))
y_test=y[num_training:]
from sklearn import linear_model
#创建线性回归对象
linear_regressor=linear_model.LinearRegression()
#用训练数据集训练模型
linear_regressor.fit(X_train,y_train)
import matplotlib.pyplot as plt
y_train_pred=linear_regressor.predict(X_train)#通过x(训练)预测y
plt.scatter(X_train,y_train,color='g')
plt.scatter(X_train,y_train_pred,color='b')
plt.plot(X_train,y_train_pred,'r-')
plt.title('training.data')
fig=plt.figure()
y_test_pred=linear_regressor.predict(X_test)#通过x(测试)预测y
plt.scatter(X_test,y_test,color='g')
plt.plot(X_test,y_test_pred,'bo-')
plt.title('testing.data')
python机器学习——线性回归
最新推荐文章于 2024-09-14 13:58:53 发布