python-3.x - Scikit-learn 标准定标器
问题描述
我希望这个问题之前没有被触及。我有一个由 18 列组成的数据集。14 列有数字数据,4 列有分类类型。我将应用线性回归算法,但在此之前我想缩放数值数据。为了做到这一点,我首先删除了分类的,缩放了数字的,然后与缩放的合并。问题是合并两个子数据集后,分类数据与训练数据集比例合并。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=5)
X_train_sub = X_train[['waterfront','view', 'basement', 'renovated']]
col_names = list(X_train_sub)
for col in col_names:
X_train_sub[col] = X_train_sub[col].astype('category',copy=False)
X_train_sub 信息()
X_train_sub.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16209 entries, 10306 to 2915
Data columns (total 4 columns):
waterfront 16209 non-null category
view 16209 non-null category
basement 16209 non-null category
renovated 16209 non-null category
dtypes: category(4)
删除分类变量后缩放训练数据
sc = StandardScaler()
X_scaled = X_train.drop(['waterfront','view', 'basement', 'renovated'], axis=1)
X_scaled = pd.DataFrame(sc.fit_transform(X_scaled),
columns=X_scaled.columns.values)
添加回列
X_scaled[['waterfront','view', 'basement', 'renovated']] = X_train_sub
X_scaled.info()
Data columns (total 18 columns):
bedrooms 16209 non-null float64
bathrooms 16209 non-null float64
sqft_living 16209 non-null float64
sqft_lot 16209 non-null float64
floors 16209 non-null float64
condition 16209 non-null float64
grade 16209 non-null float64
sqft_above 16209 non-null float64
yr_built 16209 non-null float64
zipcode 16209 non-null float64
lat 16209 non-null float64
long 16209 non-null float64
sqft_living15 16209 non-null float64
sqft_lot15 16209 non-null float64
waterfront 12143 non-null category
view 12143 non-null category
basement 12143 non-null category
renovated 12143 non-null category
dtypes: category(4), float64(14)
解决方案
我认为这是一个对齐问题。以下代码破坏了原始索引
X_scaled = pd.DataFrame(sc.fit_transform(X_scaled),
columns=X_scaled.columns.values)
尝试
X_scaled = pd.DataFrame(sc.fit_transform(X_scaled),
columns=X_scaled.columns.values,
index=X_scaled.index)
推荐阅读
- java - 仅用于打印六位数字的 Java 随机类执行
- python - 如何在特定符号处拆分长文本文件并将拆分的文件并排粘贴
- reactjs - 在反应中设置和清除输入的默认值
- django - Django 2 在模板中调用 {% url %} 后添加 URL 参数
- python - Matplotlib 图仅显示函数何时结束
- python - 如何修复 JamspellServer 中的编码错误?
- r - 如何在使用 R 中的公式的函数中使用数据框中的变量?
- html - 为 Accodion Answers 填充 0 不起作用
- python - 从一行中的字符串更改列名
- java - 没有 PreparedStatements Criteria-API 的 SQL Escape