tensorflow 做多元線性迴歸時怎樣對非資料型資料(分型別資料)進行處理(編碼)
程式碼如下:
def read_data(file_queue):
'''
the function is to get features and label (即樣本特徵和樣本的標籤)
資料來源是csv的檔案,採用tensorflow 自帶的對csv檔案的處理方式
:param file_queue:
:return: features,label
'''
# 讀取的時候需要跳過第一行
reader = tf.TextLineReader(skip_header_lines=1)
key, value = reader.read(file_queue)
# 對於資料來源中空的值設定預設值
record_defaults = [[''], [''], [''], [''], [0.], [0.], [0.], [0.], [''],[0], [''], [0.], [''], [''], [0]]
# 定義decoder,每次讀取的執行都從檔案中讀取一行。然後,decode_csv 操作將結果解析為張量列表
province, city, address, postCode, longitude,latitude, price, buildingTypeId, buildingTypeName, tradeTypeId, tradeTypeName, expectedDealPrice, listingDate, delislingDate, daysOnMarket = tf.decode_csv(value, record_defaults)
#對非數值資料進行編碼:buildingTypeName
preprocess_buildingTypeName_op = tf.case({
tf.equal(buildingTypeName, tf.constant('Residential')): lambda: tf.constant(0.00),
tf.equal(buildingTypeName, tf.constant('Condo')): lambda: tf.constant(1.00),
tf.equal(buildingTypeName, tf.constant('Mobile Home')): lambda: tf.constant(2.00),
tf.equal(buildingTypeName, tf.constant('No Building')): lambda: tf.constant(3.00),
tf.equal(buildingTypeName, tf.constant('Row / Townhouse')): lambda: tf.constant(4.00),
tf.equal(buildingTypeName, tf.constant('Duplex')): lambda: tf.constant(5.00),
tf.equal(buildingTypeName, tf.constant('Manufactured Home')): lambda: tf.constant(6.00),
tf.equal(buildingTypeName, tf.constant('Commercial')): lambda: tf.constant(7.00),
tf.equal(buildingTypeName, tf.constant('Other')): lambda: tf.constant(8.00),
}, lambda: tf.constant(-1.00), exclusive=True)
# 對tradeTypeName 進行編碼 Sale,Lease
preprocess_tradeTypeName_op = tf.case({
tf.equal(tradeTypeName, tf.constant('Sale')): lambda: tf.constant(0.00),
tf.equal(tradeTypeName, tf.constant('Lease')): lambda: tf.constant(1.00),
}, lambda: tf.constant(-1.00), exclusive=True)
features = tf.stack([latitude,longitude,price, preprocess_buildingTypeName_op, preprocess_tradeTypeName_op,expectedDealPrice])
return features, daysOnMarket
也就是通過:tf.case ,tf.equal和lambda 函式來實現