python中如何实现将数据分成训练集与测试集

接下来,直接给出大家响应的代码,并对每一行进行标注,希望能够帮到大家。

需要用到的是库是。numpy 、sklearn。

 #导入相应的库(对数据库进行切分需要用到的库是sklearn.model_selection 中的 train_test_split)
import numpy as np
from sklearn.model_selection import train_test_split
 #首先,读取.CSV文件成矩阵的形式。
my_matrix = np.loadtxt(open("xxxxxx.csv"),delimiter=",",skiprows=0)
 #对于矩阵而言,将矩阵倒数第一列之前的数值给了X(输入数据),将矩阵大最后一列的数值给了y(标签)
X, y = my_matrix[:,:-1],my_matrix[:,-1]
 #利用train_test_split方法,将X,y随机划分问,训练集(X_train),训练集标签(X_test),测试卷(y_train),
 测试集标签(y_test),安训练集:测试集=7:3的
 概率划分,到此步骤,可以直接对数据进行处理
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
 #此步骤,是为了将训练集与数据集的数据分别保存为CSV文件
 #np.column_stack将两个矩阵进行组合连接
train= np.column_stack((X_train,y_train))
 #numpy.savetxt 将txt文件保存为。csv结尾的文件
numpy.savetxt('train_usual.csv',train, delimiter = ',')
test = np.column_stack((X_test, y_test))
numpy.savetxt('test_usual.csv', test, delimiter = ',')

完整没解释的代码部分为

import numpy as np
from sklearn.model_selection import train_test_split
my_matrix = np.loadtxt(open("xxxxx.csv"),delimiter=",",skiprows=0)
X, y = my_matrix[:,:-1],my_matrix[:,-1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
train= np.column_stack((X_train,y_train))
numpy.savetxt('train_usual.csv',train, delimiter = ',')
test = np.column_stack((X_test, y_test))
numpy.savetxt('test_usual.csv', test, delimiter = ',')
posted @ 2018-03-14 15:54  keepgoon  阅读(1807)  评论(0编辑  收藏  举报