美文网首页
使用PipeLine让代码更简洁

使用PipeLine让代码更简洁

作者: 1nvad3r | 来源:发表于2020-09-24 22:07 被阅读0次
import pandas as pd
from sklearn.model_selection import train_test_split

# Read the data
X_full = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', index_col='Id')

# Remove rows with missing target, separate target from predictors
X_full.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = X_full.SalePrice
X_full.drop(['SalePrice'], axis=1, inplace=True)

# Break off validation set from training data
X_train_full, X_valid_full, y_train, y_valid = train_test_split(X_full, y, 
                                                                train_size=0.8, test_size=0.2,
                                                                random_state=0)

# "Cardinality" means the number of unique values in a column
# Select categorical columns with relatively low cardinality (convenient but arbitrary)
categorical_cols = [cname for cname in X_train_full.columns if
                    X_train_full[cname].nunique() < 10 and 
                    X_train_full[cname].dtype == "object"]

# Select numerical columns
numerical_cols = [cname for cname in X_train_full.columns if 
                X_train_full[cname].dtype in ['int64', 'float64']]

# Keep selected columns only
my_cols = categorical_cols + numerical_cols
X_train = X_train_full[my_cols].copy()
X_valid = X_valid_full[my_cols].copy()
X_test = X_test_full[my_cols].copy()

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

# Preprocessing for numerical data
numerical_transformer = SimpleImputer(strategy='constant')

# Preprocessing for categorical data
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# Bundle preprocessing for numerical and categorical data
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_cols),
        ('cat', categorical_transformer, categorical_cols)
    ])

# Define model
model = RandomForestRegressor(n_estimators=100, random_state=0)

# Bundle preprocessing and modeling code in a pipeline
clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('model', model)
                     ])

# Preprocessing of training data, fit model 
clf.fit(X_train, y_train)

# Preprocessing of validation data, get predictions
preds = clf.predict(X_valid)

print('MAE:', mean_absolute_error(y_valid, preds))

相关文章

  • 使用PipeLine让代码更简洁

  • 当RecycleView遇上DataBinding

    想让RecycleView的代码更简洁吗? 那就使用DataBinding吧~~ DataBinding可以直接将...

  • vuex的辅助函数

    辅助函数 解耦代码,可以让代码变得更简洁,只能在支持模块化的地方使用 mapState mapGetters ma...

  • Lombok让代码更简洁

    Lombok 简介 Lombok项目通过添加“处理程序”,使java成为一种更为简单的语言。 简单来说,比如我们新...

  • 让 JS 代码更简洁

    文章结尾我会附上视频地址,有自己想法的可以留言交流,谢谢? 1. 输出对象快速查看 低效输出 console.lo...

  • Spring Boot常用注解小结

    在Spring boot中,注解使用非常频繁,通过使用注解可以有效的提供开发效率,让项目代码看起来更简洁。 之前做...

  • iOS程序员手写这段代码,当场被聘用

    为什么使用RAC? 因为RAC具有高聚合低耦合的思想所以使用RAC会让代码更简洁,逻辑更清晰。 如何在项目中添加R...

  • 引言 使用JDK1.8之后,大部分list的操作都可以使用lam

    使用JDK1.8之后,大部分list的操作都可以使用lamada表达式去写,可以让代码更简洁,开发更迅速。以下是我...

  • promise

    一、promise 与 async 的区别? 1、简洁的代码 使用async函数可以让代码简洁很多,不需要像Pro...

  • 关于block

    block即代码块,将同一逻辑的代码放在一快区域中,使代码更简洁紧凑,易于阅读,而且它比函数使用更方便,代码更美观...

网友评论

      本文标题:使用PipeLine让代码更简洁

      本文链接:https://www.haomeiwen.com/subject/wprayktx.html