Spaces:
Runtime error
Runtime error
File size: 15,927 Bytes
09aad05 8767ee5 09aad05 81f39a3 09aad05 81f39a3 da07b50 d19ecaa 8067e81 81f39a3 8767ee5 09aad05 8767ee5 da07b50 8767ee5 09aad05 81f39a3 09aad05 8767ee5 da07b50 8767ee5 81f39a3 da07b50 81f39a3 09aad05 8767ee5 da07b50 8767ee5 09aad05 81f39a3 09aad05 81f39a3 8767ee5 81f39a3 d19ecaa 8767ee5 d19ecaa 8067e81 da07b50 8067e81 da07b50 8067e81 e0b1679 8067e81 da07b50 8067e81 da07b50 8067e81 8767ee5 8067e81 8767ee5 8067e81 8767ee5 |
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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 26 21:07:00 2023
@author: Bernd Ebenhoch
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import streamlit as st
from matplotlib import cm
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import mpl_toolkits.mplot3d as a3
import matplotlib.colors as colors
from matplotlib.colors import LightSource
from tensorflow import keras
import pandas as pd
from transformers import pipeline
import transformers
# Farben definieren
cb = [15/255, 25/255, 35/255]
cf = [25/255*2, 35/255*2, 45/255*2]
w = [242/255, 242/255, 242/255]
blue = [68/255, 114/255, 196/255]
orange = [197/255, 90/255, 17/255]
# Pipelines definieren
#en_de_translator = pipeline("translation_de_to_en", model='google/bert2bert_L-24_wmt_de_en')
qa_pipeline = pipeline("question-answering", model='deepset/gelectra-base-germanquad')
sentiment = pipeline("text-classification", model='oliverguhr/german-sentiment-bert')
tab1, tab2, tab3, tab4 = st.tabs(
["Künstliche Neuronale Netze", "Wortvektoren Stimmung", "Wörter Maskieren", "HuggingFace Pipelines"])
with tab1:
st.markdown(
'Definieren Sie ein neuronales Netz und beobachten Sie wie sich die Kurve krümmen kann, um die Daten zu fitten')
col1, col2 = tab1.columns(2)
size = np.array([12., 27., 32., 47., 58., 56., 58., 61.,
64., 67., 70., 80., 84., 88., 108.])
price = np.array([88., 135., 178., 216., 220., 246., 241., 275.,
305., 267., 297., 310., 292., 317., 422.])
location = np.array([2., 2., 0., 1., 2., 0., 1., 0., 1., 2., 0., 2., 1., 1., 2.])
price[location == 1] = price[location == 1]*1+30
price[location == 2] = price[location == 2]*1+60
size_location = np.concatenate((size.reshape(-1, 1), location.reshape(-1, 1)), axis=1)
data = np.concatenate((size.reshape(-1, 1), location.reshape(-1, 1),
price.reshape(-1, 1)), axis=1)
data = pd.DataFrame(data, columns=['Wohnungsgröße (qm)', 'Ort', 'Preis (k€)'])
col1.dataframe(data.style.format(precision=0))
#edited_df = st.experimental_data_editor(data)
edited_df = data
edited_data = edited_df.to_numpy()
size_location = edited_data[:, :2]
price = edited_data[:, 2]
string = col2.text_area(
'Architektur des neuronalen Netzes. Anzahl der Neuronen in den verdeckten Schichten', value='4', height=275)
layers = string.split('\n')
if st.button('Modell trainieren und Fit-Kurve darstellen'):
with st.spinner('Der Fit-Prozess kann einige Sekunden dauern ...'):
model = keras.models.Sequential()
if len(layers) > 0:
for neurons in layers:
model.add(keras.layers.Dense(int(neurons), activation='tanh'))
model.add(keras.layers.Dense(1, activation='tanh'))
model.compile(loss='binary_crossentropy', optimizer='SGD')
lr_reduction = keras.callbacks.ReduceLROnPlateau(
monitor='loss', patience=1000, min_lr=0.00001)
model.fit(size_location/[120, 2], price/500, epochs=5000,
batch_size=4, callbacks=lr_reduction, verbose=False)
y_pred = model.predict((size_location)/[120, 2], verbose=False).reshape(-1)*500
x = np.linspace(0, 125, 400)
y = np.linspace(0, 2, 400)
X, Y = np.meshgrid(x, y)
Z = np.concatenate([X.reshape(-1, 1)/120, Y.reshape(-1, 1)/2], axis=1)
Z = model.predict(Z, verbose=False)*500
Z = Z.reshape(len(y), len(x))
fig = plt.figure(facecolor=cb, figsize=(7, 7))
ax = fig.add_subplot(projection='3d')
ax.tick_params(color=w, labelcolor=w, labelsize=12)
ax.set_facecolor(cb)
ax.w_xaxis.set_pane_color(cf)
ax.w_yaxis.set_pane_color(cf)
ax.w_zaxis.set_pane_color(cf)
ax.set_yticks([0, 1, 2])
ax.view_init(25, 50)
rgb = np.tile(orange, (Z.shape[0], Z.shape[1], 1))
ls = LightSource(azdeg=315, altdeg=45, hsv_min_val=0.9,
hsv_max_val=1, hsv_min_sat=1, hsv_max_sat=0)
illuminated_surface = ls.shade_rgb(rgb, Z)
below_price = price[price < y_pred]
below_location = location[price < y_pred]
below_size = size[price < y_pred]
ax.plot(below_size, below_location, below_price, '.', markersize=20, color=blue)
ax.plot_surface(X, Y, Z, facecolors=illuminated_surface, edgecolors=[0, 0, 0, 0],
linewidth=0, antialiased=True, rcount=400, ccount=400, alpha=0.8)
above_price = price[price >= y_pred]
above_location = location[price >= y_pred]
above_size = size[price >= y_pred]
ax.plot(above_size, above_location, above_price,
'.', markersize=20, color=blue, zorder=20,)
ax.set_ylim(2, 0)
ax.set_xlim(125, 0)
ax.set_zlim(0, 450)
ax.set_xlabel('Wohnungsgröße (qm)', color=w, fontsize=15, labelpad=10)
ax.set_ylabel('Ort', color=w, fontsize=15, labelpad=10)
ax.set_zlabel('Preis (k€)', color=w, fontsize=15, rotation=270, labelpad=10)
st.pyplot(fig)
# %%
with tab2:
st.markdown(
'Definieren Sie Sätze, die positiv oder negativ gestimmt sind und beobachten Sie die resultierenden Wort-Vektoren.')
text_input_2 = '1: Das schöne Allgäu\n' + \
'1: So toll hier im Allgäu\n' + \
'1: Uns gefallen die Berge und Seen\n' + \
'1: Wir mögen die Landschaft und die Berge\n' + \
'1: Ganz toll im Allgäu\n' + \
'1: Wir mögen das Allgäu\n' + \
'0: Uns gefiel es leider nicht\n' + \
'0: Bei Regen ist es total langweilig\n' + \
'0: Ganz langweilig!\n' + \
'0: So schade, dass es oft Regen gibt\n' + \
'0: Sehr schade, wir konnten gar nicht skifahren\n' + \
'0: Das gefiel uns überhaupt nicht'
string_2 = st.text_area('', value=text_input_2, height=275)
texts_2 = string_2.split('\n')
text = []
labels = []
for element in texts_2:
if element != '':
label_element, text_element = element.split(':')
text.append(text_element)
labels.append(float(label_element))
if st.button('Modell trainieren und Wort-Vektoren darstellen', key=1):
with st.spinner('Der Fit-Prozess kann einige Sekunden dauern ...'):
vectorizer = tf.keras.layers.TextVectorization(
max_tokens=1000, output_sequence_length=7)
vectorizer.adapt(text)
model = tf.keras.models.Sequential()
model.add(vectorizer)
model.add(tf.keras.layers.Embedding(vectorizer.vocabulary_size(), 2))
# model.add(tf.keras.layers.Dropout(0.6))
model.add(tf.keras.layers.LSTM(1, return_sequences=False, activation='sigmoid'))
# model.add(tf.keras.layers.Flatten())
#model.add(tf.keras.layers.Dense(1, activation='sigmoid', use_bias=False, trainable=True))
model.summary()
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(text, labels, epochs=2000, verbose=False)
# Word Vektoren grafisch darstellen
cb = [15/255, 25/255, 35/255]
cf = [25/255*2, 35/255*2, 45/255*2]
w = [242/255, 242/255, 242/255]
blue = [68/255, 114/255, 196/255]
orange = [197/255, 90/255, 17/255]
fig = plt.figure(facecolor=cb, figsize=(7, 7))
ax = fig.add_subplot()
ax.tick_params(color=w, labelcolor=w, labelsize=12)
ax.set_facecolor(cb)
y_pred = model.predict(np.array(vectorizer.get_vocabulary(
include_special_tokens=False)).reshape(-1, 1))
embed_model = tf.keras.models.Model(model.input, model.layers[1].output)
X_embed = embed_model(np.array(vectorizer.get_vocabulary(
include_special_tokens=False)).reshape(-1, 1))[:, 0, :]
# 1. Dimension der Wort-Vektoren auf X-Achse,
# 2. Dimension auf y-Achse, 3. auf die Z-Achse abbilden
ax.scatter(X_embed[:, 0], X_embed[:, 1],
c=y_pred, cmap='coolwarm')
for i in range(vectorizer.vocabulary_size()-2):
ax.text(X_embed[i, 0], X_embed[i, 1],
vectorizer.get_vocabulary(include_special_tokens=False)[i],
color=w)
ax.set_ylim(-2, 2)
ax.set_xlim(-2, 2)
ax.set_xticks([-2, -1, 0, 1, 2])
ax.set_yticks([-2, -1, 0, 1, 2])
ax.spines['bottom'].set_color(w)
ax.spines['top'].set_color(w)
ax.spines['right'].set_color(w)
ax.spines['left'].set_color(w)
ax.set_xlabel('Dimension 1', color=w, fontsize=15, labelpad=10)
ax.set_ylabel('Dimension 2', color=w, fontsize=15, labelpad=10)
# get the mappable, the 1st and the 2nd are the x and y axes
PCM = ax.get_children()[0]
cbar = plt.colorbar(PCM, ax=ax, fraction=0.036, pad=0.090)
cbar.set_ticks([])
cbar.set_label(
'<- positiv Stimmung negativ ->', fontsize=12, color=w, rotation=270, labelpad=12)
ax.set_title('Epoche 2000', color=w, fontsize=15)
st.pyplot(fig)
# %%
with tab3:
st.markdown(
'Definieren Sie Sätze bei denen beliebige Wörter maskiert werden, um allgemeine Bezüge in Wort-Vektoren abzubilden.')
text_input = 'Das schöne Allgäu\n' + \
'Das wunderbare Allgäu\n' + \
'Das grüne Allgäu\n' + \
'Radfahren im Allgäu\n' + \
'Wandern im Allgäu\n' + \
'Radfahren in Oberschwaben\n' + \
'Urlaub in Oberschwaben\n' + \
'Künstliche Intelligenz für das Allgäu\n' + \
'Künstliche Intelligenz für Oberschwaben\n' + \
'Data Science für Oberschwaben\n' + \
'Data Science und Machine Learning\n' + \
'Machine Learning für das Allgäu'
string = st.text_area('', value=text_input, height=275)
text = string.split('\n')
if st.button('Modell trainieren und Wort-Vektoren darstellen', key=2):
with st.spinner('Der Fit-Prozess kann einige Sekunden dauern ...'):
vectorizer = tf.keras.layers.TextVectorization(
max_tokens=1000, output_sequence_length=7)
vectorizer.adapt(text)
def generator():
while True:
x = vectorizer(text)
mask = tf.reduce_max(x)+1
lengths = tf.argmin(x, axis=1)
lengths = tf.cast(lengths, tf.float32)
masks = tf.random.uniform(shape=(x.shape[0],), minval=0, maxval=lengths)
masks = tf.cast(masks, tf.int32)
masks = tf.one_hot(masks, x.shape[1], dtype=tf.int32)
masks = tf.cast(masks, tf.bool)
y = x[masks]
masks = tf.cast(masks, tf.int64)
x = x * (1-masks) + mask * masks
yield x, y
# data = tf.data.Dataset.from_tensor_slices(vectorizer(text),vectorizer(text))
# data = data.map(masking_generator)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Embedding(vectorizer.vocabulary_size()+1, 3))
model.add(tf.keras.layers.LSTM(100, return_sequences=False, activation='sigmoid'))
model.add(tf.keras.layers.Dense(vectorizer.vocabulary_size(), activation='softmax'))
model.summary()
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
lr_reduce = tf.keras.callbacks.ReduceLROnPlateau(
monitor='loss', patience=500, min_lr=1e-6)
model.fit(generator(), steps_per_epoch=1,
epochs=3000, callbacks=lr_reduce, verbose=False)
fig = plt.figure(facecolor=cb, figsize=(7, 7))
ax = fig.add_subplot()
ax.tick_params(color=w, labelcolor=w, labelsize=12)
ax.set_facecolor(cb)
embed_model = tf.keras.models.Model(model.input, model.layers[0].output)
X_embed = embed_model(vectorizer(vectorizer.get_vocabulary(
include_special_tokens=False)))[:, 0, :]
# 1. Dimension der Wort-Vektoren auf X-Achse,
# 2. Dimension auf y-Achse, 3. auf die Z-Achse abbilden
ax.scatter(X_embed[:, 0], X_embed[:, 1],
color=blue)
for i in range(vectorizer.vocabulary_size()-2):
ax.text(X_embed[i, 0], X_embed[i, 1],
vectorizer.get_vocabulary(include_special_tokens=False)[i],
color=w)
ax.set_ylim(-2, 2)
ax.set_xlim(-2, 2)
ax.set_xticks([-2, -1, 0, 1, 2])
ax.set_yticks([-2, -1, 0, 1, 2])
ax.spines['bottom'].set_color(w)
ax.spines['top'].set_color(w)
ax.spines['right'].set_color(w)
ax.spines['left'].set_color(w)
ax.set_xlabel('Dimension 1', color=w, fontsize=15, labelpad=10)
ax.set_ylabel('Dimension 2', color=w, fontsize=15, labelpad=10)
st.pyplot(fig)
# %%
with tab4:
# st.header("Übersetzung: Deutsch --> Englisch")
#st.text("Übersetzung: Deutsch --> Englisch")
st.markdown('Probieren Sie verschiedene Pipelines der Transformer-Bibliothek von HuggingFace.')
text_input_4 = 'Was ist der Schwerpunkt?'
string_4 = st.text_area('Frage zum Kontext beantworten', value=text_input_4, height=25)
text_input_5 = 'Wir unterstützen Unternehmen bei der Datenanalyse durch individuelle Beratung und Projekte mit besonderem Fokus auf maschinelles Lernen und Deep Learning.'
string_5 = st.text_area('Kontext', value=text_input_5, height=75)
if st.button('Ein fertig trainiertes Transformer-Modell von HuggingFace anwenden', key=4):
with st.spinner('Die Beantwortung der Frage kann einige Sekunden dauern ...'):
a5 = qa_pipeline(question=string_4, context=string_5)
st.text(a5)
############################################################
st.text('')
st.markdown("""<hr style="height:10px;border:none;color:#333;background-color:#333;" /> """,
unsafe_allow_html=True)
st.text('')
text_input_7 = 'Wir lieben Data Science!'
string_7 = st.text_area('Stimmungsanalyse', value=text_input_7, height=25)
if st.button('Ein fertig trainiertes Transformer-Modell von HuggingFace anwenden', key=5):
with st.spinner('Die Beurteilung der Stimmung kann einige Sekunden dauern ...'):
a5 = sentiment(string_7)
st.text(a5[0]['label'])
############################################################
st.text('')
st.markdown("""<hr style="height:10px;border:none;color:#333;background-color:#333;" /> """,
unsafe_allow_html=True)
st.text('')
references = 'Verwendete Modelle:\n' + \
'\n\nFrage beantworten:\n' + \
'deepset/gelectra-base-germanquad, Autoren: Timo Möller, Julian Risch, Malte Pietsch' + \
'\n\nStimmung:\n' + \
'oliverguhr/german-sentiment-bert, Autoren: Oliver Guhr, Anne-Kathrin Schumann, Frank Bahrmann, Hans Joachim Böhme'
st.markdown(references)
|