import plotly.express as px
dataframe = px.data.gapminder().rename(columns={
'year': 'Year',
'lifeExp': 'Life Expectancy',
'pop': 'Population',
'gdpPercap': 'GDP Per Capita'
})
@router.get('/worldviz')
async def worldviz(metric, country):
"""
Visualize world metrics from Gapminder data
### Query Parameters
- `metric`: 'Life Expectancy', 'Population', or 'GDP Per Capita'
- `country`: [country name](https://www.gapminder.org/data/geo/), case sensitive
### Response
JSON string to render with react-plotly.js
"""
subset = dataframe[dataframe.country == country]
fig = px.line(subset, x='Year', y=metric, title=f'{metric} in {country}')
return fig.to_json()
app = FastAPI(
title='House Price DS API',
description='Predict house prices in California',
docs_url='/'
)
@router.post('/predict')
async def predict(item: Item):
"""Predict house prices in California."""
y_pred = 200000
return {'predicted_price': y_pred}
import pandas as pd
from sklearn.datasets import fetch_california_housing
# Load data
california = fetch_california_housing()
print(california.DESCR)
X = pd.DataFrame(california.data, columns=california.feature_names)
y = california.target
# Rename columns
X.columns = X.columns.str.lower()
X = X.rename(columns={'avebedrms': 'bedrooms', 'averooms': 'total_rooms', 'houseage': 'house_age'})
# Explore descriptive stats
X.describe()
# Use these 3 features
features = ['bedrooms', 'total_rooms', 'house_age']
import pandas as pd
from pydantic import BaseModel
class House(BaseModel):
"""Data model to parse the request body JSON."""
bedrooms: int
total_rooms: float
house_age: float
def to_df(self):
"""Convert pydantic object to pandas dataframe with 1 row."""
return pd.DataFrame([vars(self)])
@router.post('/predict')
async def predict(house: House):
"""Predict house prices in California."""
X_new = house.to_df()
y_pred = 200000
return {'predicted_price': y_pred}