python-3.x - 无法使用 Keras 和 Sklearn 将字符串列转换为分类矩阵

标签 python-3.x pandas tensorflow keras scikit-learn

我正在尝试使用 MacOS 上的 Python3.6 构建一个简单的 Keras 模型,以预测给定范围内的房价,但我未能将输出转换为类别矩阵。我正在使用 this dataset来自 Kaggle。

我在数据框中创建了一个新列,将不同的价格范围作为字符串作为我的模型中的目标输出,然后使用 keras.utils 和 Sklearn LabelEncoder 尝试创建输出二进制矩阵,但我不断收到错误消息:

ValueError: invalid literal for int() with base 10: '0 - 50000'

这是我的代码:
import pandas as pd
import numpy as np
from keras.layers import Dense
from keras.models import Sequential, load_model
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical, np_utils
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder

seed = 7
np.random.seed(seed)

data = pd.read_csv("Melbourne_housing_FULL.csv")
data.fillna(0, inplace=True)

price_range = 50000
bins = np.arange(0, 12000000, price_range)
labels = ['{} - {}'.format(i + 1, j) for i, j in zip(bins[:-1], bins[1:])] 

#correct first value 
labels[0] = '0 - 50000'

for item in labels:
    str(item)

print (labels[:10])
['0 - 50000', '50001 - 100000', '100001 - 150000', '150001 - 200000', 
 '200001 - 250000', '250001 - 300000', '300001 - 350000', '350001 - 400000', 
 '400001 - 450000', '450001 - 500000']

data['PriceRange'] = pd.cut(data.Price, 
                            bins=bins, 
                            labels=labels, 
                            right=True, 
                            include_lowest=True)

#print(data.PriceRange.value_counts())
output_len = len(labels)
print(output_len)

在我运行下一段之前,这里一切都是正确的:
predictors = data.drop(['Suburb', 'Address', 'SellerG', 'CouncilArea', 
                        'Propertycount', 'Date', 'Type', 'Price', 'PriceRange'], axis=1).as_matrix()

target = data['PriceRange']


# encode class values as integers
encoder = LabelEncoder()
encoder.fit(target)
encoded_Y = encoder.transform(target)

target = np_utils.to_categorical(data.PriceRange)

n_cols = predictors.shape[1]

我得到 ValueError: invalid literal for int() with base 10: '0 - 50000'

有人帮我吗?真的不明白我做错了什么。

非常感谢

最佳答案

因为np_utils.to_categorical接受 y 的数据类型 int,但你有字符串要么通过给它们一个键将它们转换为 int,即:

cats = data.PriceRange.values.categories
di = dict(zip(cats,np.arange(len(cats))))
#{'0 - 50000': 0,
# '10000001 - 10050000': 200,
# '1000001 - 1050000': 20,
# '100001 - 150000': 2,
# '10050001 - 10100000': 201,
# '10100001 - 10150000': 202,

target = np_utils.to_categorical(data.PriceRange.map(di))

或者因为您使用的是 Pandas ,您可以使用 pd.get_dummies获得一种热编码。
onehot = pd.get_dummies(data.PriceRange)
target_labels = onehot.columns
target = onehot.as_matrix()

array([[ 1.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 1.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])

关于python-3.x - 无法使用 Keras 和 Sklearn 将字符串列转换为分类矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573293/

相关文章:

python - 迭代两个 pandas 数据帧之间的日期范围以获取类别计数

python - Pandas 将 if-then 语句应用于矩阵 df

python - tensorflow 稀疏分类交叉熵与 logits

c++ - Bazel Link .so 库位于一个完全不同的、非常远程的文件夹中

python-3.x - Google Finance API 的日期参数不起作用

python-3.x - 如何在 Spacy 中使用神经核函数

python - 使用 Azure 托管服务标识 (MSI) 连接 Azure SQL Server 数据库

python - 如何构建我的 Python 项目以允许从子目录导入命名模块

python - XlsxWriter 和 Pandas 中的列名问题

python - 类型错误 : fit_generator() got an unexpected keyword argument 'nb_val_samples'