위도 및 경도 Feature Engineering 케이스 정리

Data Setup

import polars as pl  
from xgboost import XGBRegressor  
from sklearn.linear_model import Ridge  
  
  
# Data taken from https://www.openml.org/search?type=data&id=43093  
df = (  
	pl.scan_csv("../data/miami-housing.csv")  
	.with_columns([  
		pl.col("SALE_PRC").alias("price"),  
		pl.col(["LATITUDE", "LONGITUDE"]).name.to_lowercase()  
	])  
	.select(pl.col(["latitude", "longitude", "price"]))  
)

TRAIN_TEST_SPLIT_FRACTION = 0.8  
  
df = (  
	df  
	  
	# Shuffle the data to avoid any issues from the data being pre-ordered...  
	.sample(fraction=1, shuffle=True)  
	  
	# ...then use row numbers as an index for separating train and test.  
	.with_row_count(name="row_number")  
	.with_columns([  
	(pl.col("row_number") < TRAIN_TEST_SPLIT_FRACTION * len(df)).alias("is_train")  
	])  
)

Feature Engineering

  • Raw Latitude and Longitude
  • Spatial Density
    • Population density is correlated with many demographic processes, and this is certainly true for rental prices and incomes.
    • Approach
      • One could use many methods for measuring the spatial density around a home: counting the number of other home sales within some radius of each home sale
      • or computing and sampling from a Kernel Density Estimate over home sale locations
      • or even pulling third party census data about population density.
    • Case(scipy's CKDTree 이용해서 Density Feature 생성)

def add_density_feature_columns_to_dataframe(geo_df: pl.DataFrame) -> pl.DataFrame:  
	tree = spatial.cKDTree(df.select(["latitude", "longitude"]))  
	result = geo_df.with_columns(  
	pl.Series(  
	"spatial_density",  
	tree.query_ball_point(geo_df.select(["latitude", "longitude"]), .005, return_length=True)  
	)  
	)  
	return result  
  
  
df_w_density = add_density_feature_columns_to_dataframe(df)
  • Geohash Target Encoding(Ref)
    • It’s a known fact — some neighborhoods are more expensive than others. So, it’s possible that giving information to the model about each home’s neighborhood (and the sale price that can be expected in that neighborhood) can add predictive power.
    • A neighborhood can be anything — a zip-code, a street, or in our case, a Geohash.
def add_geohash_column_to_df(geo_df: pl.DataFrame) -> pl.DataFrame:  
	result = (  
	df  
		.with_columns(  
			df  
				.select("latitude", "longitude")  
				.map_rows(  
					lambda x: geohash2.encode(x[0], x[1], precision=5),  
					return_dtype=pl.Utf8  
			)  
		.rename({"map": "geohash"})  
		)  
	)  
	return result  
  
def add_target_encoding_to_df(  
		dataframe: pl.DataFrame,  
		categorical_column: str = "geohash"  
	) -> pl.DataFrame:  
		category_target_means = (  
		dataframe  
		.filter(pl.col("is_train")) # Only include train data to prevent test data leakage.  
		.group_by(categorical_column)  
		.agg(  
			pl.col(MODEL_TARGET).mean().alias(f"{categorical_column}_{MODEL_TARGET}_mean")  
		)  
	)  
	result = (  
		dataframe  
		.join(  
			category_target_means,  
			how="left",  
			on=categorical_column  
		)  
	)  
	return result  
  
df_w_geohash = add_geohash_column_to_df(df)  
df_w_geohash_target_encoded = add_target_encoding_to_df(df_w_geohash)

Reference

Read more

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

장강명 작가의 책은, 유학시절 읽고 처음이었다. 유학시절 "한국이 싫어서"라는 책은 동기부여가 상당히 되는 책이었다. 한국을 떠나 새로운 정채성을 학생으로서 Build up 해나가고 있던 상황에서 이 책은 제목부터 꽤 솔깃하였다. 물론 결말이 기억날 정도로 인상깊은 책은 아니었지만 말이다. 그렇게 시간이 흘러 장강명 작가의 책은 더 이상 읽지 않던

By Bongho, Lee
고객 경험이란 무엇일까?

고객 경험이란 무엇일까?

고객경험이란 무엇일까? 1. 과거 어느 대형 프로젝트에서 있던 일이다. 신사업을 위해서 예측 모델 값을 제공해야 하는 상황이었다. 데이터도 없고,어느정도의 정확도를 제공해야 하는지 답이 없었다. 점추정을 할 것인가? 구간 추정을 할 것인가를 가지고 논의중이었다. Product Manager 줄기차게 고객경험을 내세우며 점추정으로 해야 한다고 주장하였다. 근거는 오롯이 "고객 경험"이었다.

By Bongho, Lee
수요예측, 수정구슬이 아닌 목표를 향한 냉정한 나침반

수요예측, 수정구슬이 아닌 목표를 향한 냉정한 나침반

수요예측의 정의와 비즈니스에서의 중요성 기업의 성장과 운영 효율화를 위해 **수요예측(Demand Forecasting)**은 선택이 아닌 필수 요소로 자리 잡았다. 많은 경영진들이 수요예측을 미래 판매량을 정확히 맞히는 '예언'으로 기대하지만, 이는 수요예측의 본질을 오해하는 것이다. 수요예측의 진짜 의미: 미래를 점치는 수정구슬이 아니라, 우리가 도달해야 할 '목표'를

By Bongho, Lee