我试图理解来自machinelearningmastery.com的一些示例代码,但是切片符号让我望而却步...对于使用我的代码的初学者来说,我试图使用来自CSV文件的一些数据制作简单的回归类型ML算法:
import pandas as pd
McheLrn = pd.read_csv('C:/Users/data.csv', index_col='Date', parse_dates=True)
McheLrn['month'] = McheLrn.index.month
McheLrn['date'] = McheLrn.index.strftime('%d')
McheLrn['hour'] = McheLrn.index.strftime('%H')
McheLrn['Day_of_week'] = McheLrn.index.dayofweek
McheLrn.head()
这将输出:
OSAT kWh month date hour Day_of_week
Date
2013-01-01 06:00:00 10.4 16.55 1 01 06 1
2013-01-01 06:15:00 10.4 16.55 1 01 06 1
2013-01-01 06:30:00 10.4 16.05 1 01 06 1
2013-01-01 06:35:00 10.4 16.05 1 01 06 1
2013-01-01 06:45:00 10.4 17.20 1 01 06 1
不知道我是否使用正确的术语,但是因变量是
kWh
(Y变量),而其他所有变量都是我的X变量的自变量...在下面的代码中,切片符号
X = array[:,0:2] Y = array[:,2]
让我大跌眼镜。我不确定我是否正确选择了X和Y变量。# Decision Tree Regression
import pandas
from sklearn import model_selection
from sklearn.tree import DecisionTreeRegressor
dataframe = McheLrn
array = dataframe.values
X = array[:,0:2]
Y = array[:,2]
seed = 7
kfold = model_selection.KFold(n_splits=90, random_state=seed)
model = DecisionTreeRegressor()
scoring = 'neg_mean_squared_error'
results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
print(results.mean())
最佳答案
只是为了进一步说明。如果您知道目标列(名称),则首选方法是选择除目标列之外的所有内容,例如:
df=pd.DataFrame({'a':[1,2],'b':[2,3],'c':[1,9]})
target_col=['c'] # column 'c' is the target column here
X=df[list(set(df.columns).difference(target_col))].values # X-> features
Y=df[target_col].values # Y -> target
如果使用列号。假设最后一列是目标列
data=df.values
X=data[:,:2] # from column 1 upto second last column including all the rows
Y=data[:,2] # only last column(target) including all the rows