Bernd-Ebenhoch commited on
Commit
09aad05
·
1 Parent(s): e005fbe

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +243 -0
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sun Mar 26 21:07:00 2023
4
+
5
+ @author: Bernd Ebenhoch
6
+ """
7
+
8
+
9
+ import tensorflow as tf
10
+ import numpy as np
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib import animation
13
+ from matplotlib.animation import FuncAnimation
14
+ import matplotlib as mpl
15
+ import streamlit as st
16
+
17
+ from matplotlib import cm
18
+
19
+ import matplotlib.pyplot as plt
20
+ from sklearn.linear_model import LinearRegression
21
+ import mpl_toolkits.mplot3d as a3
22
+ import matplotlib.colors as colors
23
+ from matplotlib.colors import LightSource
24
+ from tensorflow import keras
25
+ import pandas as pd
26
+
27
+
28
+ # Farben definieren
29
+ cb = [15/255, 25/255, 35/255]
30
+ cf = [25/255*2, 35/255*2, 45/255*2]
31
+ w = [242/255, 242/255, 242/255]
32
+ blue = [68/255, 114/255, 196/255]
33
+ orange = [197/255, 90/255, 17/255]
34
+
35
+ tab1, tab2, tab3 = st.tabs(["Künstliche Neuronale Netze", "Wörter Maskieren", "Demos"])
36
+
37
+
38
+ with tab1:
39
+ col1, col2 = tab1.columns(2)
40
+ size = np.array([12., 27., 32., 47., 58., 56., 58., 61.,
41
+ 64., 67., 70., 80., 84., 88., 108.])
42
+ price = np.array([88., 135., 178., 216., 220., 246., 241., 275.,
43
+ 305., 267., 297., 310., 292., 317., 422.])
44
+ location = np.array([2., 2., 0., 1., 2., 0., 1., 0., 1., 2., 0., 2., 1., 1., 2.])
45
+ price[location == 1] = price[location == 1]*1+30
46
+ price[location == 2] = price[location == 2]*1+60
47
+
48
+ size_location = np.concatenate((size.reshape(-1, 1), location.reshape(-1, 1)), axis=1)
49
+
50
+ data = np.concatenate((size.reshape(-1, 1), location.reshape(-1, 1),
51
+ price.reshape(-1, 1)), axis=1)
52
+ data = pd.DataFrame(data, columns=['Wohnungsgröße (qm)', 'Ort', 'Preis (k€)'])
53
+
54
+ col1.dataframe(data.style.format(precision=0))
55
+ #edited_df = st.experimental_data_editor(data)
56
+ edited_df = data
57
+
58
+ edited_data = edited_df.to_numpy()
59
+ size_location = edited_data[:, :2]
60
+ price = edited_data[:, 2]
61
+
62
+ string = col2.text_area(
63
+ 'Architektur des neuronalen Netzes. Anzahl der Neuronen in den einzelnen Schichten', value='4', height=275)
64
+ layers = string.split('\n')
65
+
66
+ if st.button('Modell trainieren und Fit-Kurve darstellen'):
67
+
68
+ with st.spinner('Der Fit-Prozess kann einige Sekunden dauern ...'):
69
+
70
+ model = keras.models.Sequential()
71
+
72
+ if len(layers) > 0:
73
+ for neurons in layers:
74
+ model.add(keras.layers.Dense(int(neurons), activation='tanh'))
75
+ model.add(keras.layers.Dense(1, activation='tanh'))
76
+
77
+ model.compile(loss='binary_crossentropy', optimizer='SGD')
78
+
79
+ lr_reduction = keras.callbacks.ReduceLROnPlateau(
80
+ monitor='loss', patience=1000, min_lr=0.00001)
81
+
82
+ model.fit(size_location/[120, 2], price/500, epochs=5000,
83
+ batch_size=4, callbacks=lr_reduction, verbose=False)
84
+
85
+ y_pred = model.predict((size_location)/[120, 2], verbose=False).reshape(-1)*500
86
+
87
+ x = np.linspace(0, 125, 400)
88
+ y = np.linspace(0, 2, 400)
89
+ X, Y = np.meshgrid(x, y)
90
+
91
+ Z = np.concatenate([X.reshape(-1, 1)/120, Y.reshape(-1, 1)/2], axis=1)
92
+ Z = model.predict(Z, verbose=False)*500
93
+
94
+ Z = Z.reshape(len(y), len(x))
95
+
96
+ fig = plt.figure(facecolor=cb, figsize=(7, 7))
97
+ ax = fig.add_subplot(projection='3d')
98
+ ax.tick_params(color=w, labelcolor=w, labelsize=12)
99
+ ax.set_facecolor(cb)
100
+
101
+ ax.w_xaxis.set_pane_color(cf)
102
+ ax.w_yaxis.set_pane_color(cf)
103
+ ax.w_zaxis.set_pane_color(cf)
104
+
105
+ ax.set_yticks([0, 1, 2])
106
+ ax.view_init(25, 50)
107
+
108
+ rgb = np.tile(orange, (Z.shape[0], Z.shape[1], 1))
109
+
110
+ ls = LightSource(azdeg=315, altdeg=45, hsv_min_val=0.9,
111
+ hsv_max_val=1, hsv_min_sat=1, hsv_max_sat=0)
112
+ illuminated_surface = ls.shade_rgb(rgb, Z)
113
+
114
+ below_price = price[price < y_pred]
115
+ below_location = location[price < y_pred]
116
+ below_size = size[price < y_pred]
117
+
118
+ ax.plot(below_size, below_location, below_price, '.', markersize=20, color=blue)
119
+
120
+ ax.plot_surface(X, Y, Z, facecolors=illuminated_surface, edgecolors=[0, 0, 0, 0],
121
+ linewidth=0, antialiased=True, rcount=400, ccount=400, alpha=0.8)
122
+
123
+ above_price = price[price >= y_pred]
124
+ above_location = location[price >= y_pred]
125
+ above_size = size[price >= y_pred]
126
+
127
+ ax.plot(above_size, above_location, above_price,
128
+ '.', markersize=20, color=blue, zorder=20,)
129
+
130
+ ax.set_ylim(2, 0)
131
+ ax.set_xlim(125, 0)
132
+ ax.set_zlim(0, 450)
133
+
134
+ ax.set_xlabel('Wohnungsgröße (qm)', color=w, fontsize=15, labelpad=10)
135
+ ax.set_ylabel('Ort', color=w, fontsize=15, labelpad=10)
136
+ ax.set_zlabel('Preis (k€)', color=w, fontsize=15, rotation=270, labelpad=10)
137
+
138
+ st.pyplot(fig)
139
+
140
+
141
+ # %%
142
+ with tab2:
143
+
144
+ text_input = 'Das schöne Allgäu\n' + \
145
+ 'Das wunderbare Allgäu\n' + \
146
+ 'Das grüne Allgäu\n' + \
147
+ 'Radfahren im Allgäu\n' + \
148
+ 'Wandern im Allgäu\n' + \
149
+ 'Radfahren in Oberschwaben\n' + \
150
+ 'Urlaub in Oberschwaben\n' + \
151
+ 'Künstliche Intelligenz für das Allgäu\n' + \
152
+ 'Künstliche Intelligenz für Oberschwaben\n' + \
153
+ 'Data Science für Oberschwaben\n' + \
154
+ 'Data Science und Machine Learning\n' + \
155
+ 'Machine Learning für das Allgäu'
156
+
157
+ string = st.text_area('', value=text_input, height=275)
158
+ text = string.split('\n')
159
+
160
+ if st.button('Modell trainieren und Wort-Vektoren darstellen'):
161
+ with st.spinner('Der Fit-Prozess kann einige Sekunden dauern ...'):
162
+
163
+ vectorizer = tf.keras.layers.TextVectorization(
164
+ max_tokens=1000, output_sequence_length=7)
165
+
166
+ vectorizer.adapt(text)
167
+
168
+ def generator():
169
+ while True:
170
+ x = vectorizer(text)
171
+ mask = tf.reduce_max(x)+1
172
+
173
+ lengths = tf.argmin(x, axis=1)
174
+ lengths = tf.cast(lengths, tf.float32)
175
+
176
+ masks = tf.random.uniform(shape=(x.shape[0],), minval=0, maxval=lengths)
177
+ masks = tf.cast(masks, tf.int32)
178
+
179
+ masks = tf.one_hot(masks, x.shape[1], dtype=tf.int32)
180
+ masks = tf.cast(masks, tf.bool)
181
+
182
+ y = x[masks]
183
+ masks = tf.cast(masks, tf.int64)
184
+ x = x * (1-masks) + mask * masks
185
+ yield x, y
186
+
187
+ # data = tf.data.Dataset.from_tensor_slices(vectorizer(text),vectorizer(text))
188
+ # data = data.map(masking_generator)
189
+ model = tf.keras.models.Sequential()
190
+
191
+ model.add(tf.keras.layers.Embedding(vectorizer.vocabulary_size()+1, 3))
192
+
193
+ model.add(tf.keras.layers.LSTM(100, return_sequences=False, activation='sigmoid'))
194
+ model.add(tf.keras.layers.Dense(vectorizer.vocabulary_size(), activation='softmax'))
195
+
196
+ model.summary()
197
+
198
+ model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
199
+ metrics=['accuracy'])
200
+
201
+ lr_reduce = tf.keras.callbacks.ReduceLROnPlateau(
202
+ monitor='loss', patience=500, min_lr=1e-6)
203
+ model.fit(generator(), steps_per_epoch=1,
204
+ epochs=3000, callbacks=lr_reduce, verbose=False)
205
+
206
+ fig = plt.figure(facecolor=cb, figsize=(7, 7))
207
+ ax = fig.add_subplot()
208
+ ax.tick_params(color=w, labelcolor=w, labelsize=12)
209
+ ax.set_facecolor(cb)
210
+
211
+ embed_model = tf.keras.models.Model(model.input, model.layers[0].output)
212
+ X_embed = embed_model(vectorizer(vectorizer.get_vocabulary(
213
+ include_special_tokens=False)))[:, 0, :]
214
+
215
+ # 1. Dimension der Wort-Vektoren auf X-Achse,
216
+ # 2. Dimension auf y-Achse, 3. auf die Z-Achse abbilden
217
+ ax.scatter(X_embed[:, 0], X_embed[:, 1],
218
+ color=blue)
219
+ for i in range(vectorizer.vocabulary_size()-2):
220
+ ax.text(X_embed[i, 0], X_embed[i, 1],
221
+ vectorizer.get_vocabulary(include_special_tokens=False)[i],
222
+ color=w)
223
+
224
+ ax.set_ylim(-2, 2)
225
+ ax.set_xlim(-2, 2)
226
+
227
+ ax.set_xticks([-2, -1, 0, 1, 2])
228
+ ax.set_yticks([-2, -1, 0, 1, 2])
229
+
230
+ ax.spines['bottom'].set_color(w)
231
+ ax.spines['top'].set_color(w)
232
+ ax.spines['right'].set_color(w)
233
+ ax.spines['left'].set_color(w)
234
+
235
+ ax.set_xlabel('Dimension 1', color=w, fontsize=15, labelpad=10)
236
+ ax.set_ylabel('Dimension 2', color=w, fontsize=15, labelpad=10)
237
+
238
+ st.pyplot(fig)
239
+
240
+
241
+ # %%
242
+ with tab3:
243
+ st.header("An owl")