위도 및 경도 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

[책]Reshuffle: Who wins when AI restacks the knowledge economy

[책]Reshuffle: Who wins when AI restacks the knowledge economy

원래는 Amazon에 가서 Personal Knowledge Managment에 관한 책을 사려고 했다. Sketch Your Mind라는 책이었는데, 그 때 이 책 “Reshuffle”을 발견하였다. AI가 어떻게 Knowledge Economy를 흔들 것가? 라는 부제를 훑어보면서 저자가 쓴 다른 책을 보게 되었는데 거기에 내가 좋아했던 책을쓴 저자라는 것을 알게 되었다. 그래서 크게 고민하지 않고 구매를 하고

By Bongho, Lee
[책]올라운드투자, 누군가의 투자일기

[책]올라운드투자, 누군가의 투자일기

“올라운드 투자”라는 제목을 보았을 때는, “올라운드 플레이어”가 생각이 났다. “올라운드”라는 표현을 오랜만에 들어본 까닭이었다. 그럼에도 불구하고 이 책을 고른 것은 저자가 그간 보여준 컨텐츠에 대한 신뢰가 있던 까닭이었다. 컨텐츠를 다양하게 보는 편이지만 깊이가 아주 있지는 않았다. 여기서 깊이라 함은 기존 전문적인 정량적 분석의 내용의 수준을 말하는 것이다.

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

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

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

By Bongho, Lee