ML5

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
„““
Created on Wed Mar 3 10:58:27 2021
Keras Modell Zeitreihe ml 5 Versicherung
@author: guttmann
„““
import pandas as pd
df = pd.read_csv(„insurance.csv“)
print(df.head)
X=df[[‚age‘,’bmi‘,’children‘]].values
y=df[[‚charges‘]].values
#…………Normierung
from sklearn.preprocessing import StandardScaler
scaler_X=StandardScaler()
X=scaler_X.fit_transform(X)
scaler_y=StandardScaler()
y=scaler_y.fit_transform(y)
#…………….Modell
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(units=1, input_shape=(3,)))
model.summary()
model.compile(loss=’mse‘,metrics=[‚accuracy‘],optimizer=’sgd‘)
history=model.fit(X,y, epochs=5,batch_size=32)
#…………..Modell speichern
model.save(„ML5.h5“)
#…………..Evaluation
from sklearn.metrics import r2_score
y_pred=model.predict(X)
r2=r2_score(y,y_pred)
print(‚Evaluation : ‚,’r2={:.3f}‘.format(r2))
print(‚Gewichte :‘,model.get_layer(index=0).get_weights())
#…………….Prediction
X_pred=[[40.,20.1,1.]] #40 jahre, bmi 20.2, 1 kind
X_pred=scaler_X.transform(X_pred)
y_pred=model.predict(X_pred)
y_pred=scaler_y.inverse_transform(y_pred)
print (‚loss : ‚,history.history[‚loss‘])
print (‚accuracy : ‚,history.history[‚accuracy‘])
print (‚keys : ‚,history.history.keys())
print (‚Vorhersage : ‚,y_pred)

#…………..Funktion plotten
import matplotlib.pyplot as plt
plt.plot(history.history[‚loss‘])
plt.plot(history.history[‚accuracy‘]),plt.legend([‚train‘, ‚test‘], loc=’upper right‘)
plt.title(‚model accuracy‘)
plt.ylabel(‚accuracy‘),plt.xlabel(‚epoch‘)
plt.show()
# summarize history for loss
plt.plot(history.history[‚loss‘])
plt.title(‚model loss‘),plt.legend([‚train‘, ‚test‘], loc=’upper right‘)
plt.ylabel(‚loss‘),plt.xlabel(‚epoch‘)
plt.show()