Spaces:
Runtime error
Runtime error
File size: 4,529 Bytes
4f30b91 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
import datetime
import time
import altair as alt
import pandas as pd
import streamlit as st
from sklearn.linear_model import LinearRegression
st.set_page_config(page_title="Predicción de nuevos puestos de trabajo",
page_icon=":bar_chart:", layout="wide")
st.title('Predicción de nuevos puestos de trabajo')
# Cargar los datos
df = pd.read_csv('/home/catriel/Documents/data_world_jobs/data/ds_salaries.csv')
# Seleccionar las columnas relevantes
df_relevant = df[['job_title', 'work_year']]
# Transformar la columna work_year en un tipo date en la columna date
df_relevant['date'] = pd.to_datetime(df_relevant['work_year'], format='%Y')
# Agregar una columna con el año de creación
df_relevant['year'] = pd.DatetimeIndex(df_relevant['date']).year
# Contar la cantidad de job_title creados por año
job_title_count = df_relevant.groupby('year').count()['job_title']
# Crear un dataframe con la cantidad de job_title creados por año
df_job_title_count = pd.DataFrame(
{'year': job_title_count.index, 'job_title_count': job_title_count.values})
# Crear un modelo de regresión lineal
model = LinearRegression()
# Entrenar el modelo con los datos históricos
X = df_job_title_count[['year']]
y = df_job_title_count['job_title_count']
model.fit(X, y)
# Obtener el año actual
current_year = datetime.datetime.now().year
# Predecir la cantidad de nuevos job_title que se crearán este año
current_year_input = st.number_input('Ingresa un año:', value=current_year,
min_value=current_year,
max_value=2050, step=1)
if current_year_input < current_year:
st.warning('Solo se pueden hacer predicciones para años futuros.')
current_year_input = current_year
st.write('Se usará el año actual:', current_year_input)
with st.spinner('Prediciendo...'):
time.sleep(1)
job_title_count_pred = model.predict([[current_year_input]])
# Obtener el último año del dataset
last_year = df_job_title_count['year'].max()
last_year_count = \
df_job_title_count.loc[df_job_title_count['year'] == last_year][
'job_title_count'].values[0]
# Mostrar resultados
st.write(
"Se crearán aproximadamente **{}** nuevos puestos de trabajo este año **{}**.".format(
int(job_title_count_pred), current_year_input))
percentage_change = (
job_title_count_pred - last_year_count) / last_year_count * 100
percentage_change = float(percentage_change)
if percentage_change >= 0:
st.write(
"Esto representa un aumento del {:.2f}% con respecto al año {}.".format(
percentage_change, last_year))
else:
st.write(
"Esto representa una disminución del {:.2f}% con respecto al año {}".format(
abs(percentage_change), last_year))
# Crear un gráfico de línea
line_chart = alt.Chart(df_job_title_count).mark_line().encode(
x='year',
y='job_title_count'
).properties(
title='Cantidad de nuevos puestos de trabajo por año',
width=700,
height=400
).configure_axis(
labelFontSize=14,
titleFontSize=16
)
# Crear un punto para mostrar el valor predicho
point = alt.Chart(df_job_title_count.iloc[-1:]).mark_point(color='#5c62ac').encode(
x='year',
y='job_title_count'
)
# Mostrar la gráfica actualizada con el valor predicho para el año ingresado
# st.altair_chart(line_chart, use_container_width=True)
# Crear botón para graficar la predicción
if st.button('Mostrar gráfico de predicción'):
# Crear dataframe con los años y las predicciones
years = list(range(last_year, current_year + current_year_input - 2000))
predictions = model.predict([[year] for year in years])
df_predictions = pd.DataFrame(
{'year': years, 'job_title_count_pred': predictions})
# Crear gráfico de línea
line_chart = alt.Chart(df_predictions).mark_line().encode(
x='year',
y='job_title_count_pred'
).properties(
width=1200,
height=600
)
# Agregar capa con punto rojo en el valor predicho para el año actual
current_year_pred = int(model.predict([[current_year_input]])[0])
point_chart = alt.Chart(pd.DataFrame(
{'x': [current_year_input], 'y': [current_year_pred]})).mark_point(
color='#5c62ac',
size=300,
stroke='#5c62ac',
strokeWidth=5).encode(
x='x',
y='y'
)
# Mostrar gráfico con la capa adicional del punto rojo
st.altair_chart(line_chart + point_chart) |