Monday, June 6, 2022

Building Neural Networks with Keras

 Code source

(.env) boris@boris-All-Series:~/MATPLOTLIBSR/TAXI$ cat taxifareMLP.py

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

sns.set()

  

df = pd.read_csv('taxi-fares.csv')

# print(df.head())

import datetime

from math import sqrt

df = df[df['passenger_count'] == 1]

df = df.drop(['key', 'passenger_count'], axis=1)

 

for i, row in df.iterrows():

    dt = datetime.datetime.strptime(row['pickup_datetime'], '%Y-%m-%d %H:%M:%S UTC')

    df.at[i, 'day_of_week'] = dt.weekday()

    df.at[i, 'pickup_time'] = dt.hour

    x = (row['dropoff_longitude'] - row['pickup_longitude']) * 54.6

    y = (row['dropoff_latitude'] - row['pickup_latitude']) * 69.0

    distance = sqrt(x**2 + y**2)

    df.at[i, 'distance'] = distance

 

df.drop(['pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude'], axis=1, inplace=True)

df = df[(df['distance'] > 1.0) & (df['distance'] < 10.0)]

df = df[(df['fare_amount'] > 0.0) & (df['fare_amount'] < 50.0)]

print(df.head())


from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Dense

model = Sequential()

model.add(Dense(512, activation='relu', input_dim=3))

model.add(Dense(512, activation='relu'))

model.add(Dense(1))

model.compile(optimizer='adam', loss='mae', metrics=['mae'])

print(model.summary())


x = df.drop('fare_amount', axis=1)

y = df['fare_amount']

hist = model.fit(x, y, validation_split=0.2, epochs=100, batch_size=100)

err = hist.history['mae']

val_err = hist.history['val_mae']

epochs = range(1, len(err) + 1)

plt.plot(epochs, err, '-', label='Training MAE')

plt.plot(epochs, val_err, ':', label='Validation MAE')

plt.title('Training and Validation Accuracy')

plt.xlabel('Epoch')

plt.ylabel('Mean Absolute Error')

plt.legend(loc='upper right')

plt.plot()

plt.show()



















































References

https://www.atmosera.com/blog/building-neural-networks-with-keras-and-tensorflow/




No comments:

Post a Comment