Monday 30 September 2019

neural network 8 chatbot

#chatbot cheat sheet

{"intents": [
        {"tag": "greeting",
         "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day", "Whats up"],
         "responses": ["Hello!", "Good to see you again!", "Hi there, how can I help?"],
         "context_set": ""
        },
        {"tag": "goodbye",
         "patterns": ["cya", "See you later", "Goodbye", "I am Leaving", "Have a Good day"],
         "responses": ["Sad to see you go :(", "Talk to you later", "Goodbye!"],
         "context_set": ""
        },
        {"tag": "age",
         "patterns": ["how old", "how old is tim", "what is your age", "how old are you", "age?"],
         "responses": ["I am 18 years old!", "18 years young!"],
         "context_set": ""
        },
        {"tag": "name",
         "patterns": ["what is your name", "what should I call you", "whats your name?"],
         "responses": ["You can call me Tim.", "I'm Tim!", "I'm Tim aka Tech With Tim."],
         "context_set": ""
        },
        {"tag": "shop",
         "patterns": ["Id like to buy something", "whats on the menu", "what do you reccommend?", "could i get something to eat"],
         "responses": ["We sell chocolate chip cookies for $2!", "Cookies are on the menu!"],
         "context_set": ""
        },
        {"tag": "hours",
         "patterns": ["when are you guys open", "what are your hours", "hours of operation"],
         "responses": ["We are open 7am-4pm Monday-Friday!"],
         "context_set": ""
        }
   ]
}

--------------------------------------
#cmd
#tflearn doesn't work with python 3.7, uninstall and reinstall python 3.6.x instead

pip install nltk
pip install numpy
pip install tflearn
pip install tensorflow

--------------------------------
#pycharm
#load data

import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json

with open('intents.json') as file:
    data = json.load(file)

#print(data['intents'])
words = []
labels = []
docs_pattern = []
docs_tag = []

for intent in data['intents']:
    for pattern in intent['patterns']:
        #get all the words in pattern
        wds = nltk.word_tokenize(pattern)
        #copy word list to words[]
        words.extend(wds)
        #used for input of neural network
        docs_pattern.append(wds)
        #copy cosresponding category, used as output of neural network
        docs_tag.append(intent['tag'])
        #copy categories into labels[]
        if(intent['tag'] not in labels):
            labels.append(intent['tag'])

#format words so that they don't contain symbols...
words = [stemmer.stem(w.lower()) for w in words if w != '?']
#remove duplicate words, sort
words = sorted(list(set(words)))
labels = sorted(labels)
#one hot encoding, if input entry word exists in dictionary, mark 1 else 0
training = []
output = []
#output default [0,0,0...] length = # of categories
out_empty =[0 for _ in range(len(labels))]
#print(words, labels, out_empty)
#print(docs_pattern, docs_tag)

--------------------------------
#logs

#words (AI input dictionary)

['a', 'ag', 'am', 'anyon', 'ar', 'buy', 'cal', 'could', 'cya', 'day', 'do', 'eat', 'get', 'good', 'goodby', 'guy', 'hav', 'hello', 'hi', 'hour', 'how', 'i', 'id', 'is', 'lat', 'leav', 'lik', 'menu', 'nam', 'of', 'old', 'on', 'op', 'reccommend', 'see', 'should', 'someth', 'the', 'ther', 'tim', 'to', 'up', 'what', 'when', 'yo', 'you']

#labels (AI output categories)

['age', 'goodbye', 'greeting', 'hours', 'name', 'shop']

#doc_patterns (training data input, from AI cheat sheet)

[['Hi'], ['How', 'are', 'you'], ['Is', 'anyone', 'there', '?'], ['Hello'], ['Good', 'day'], ['Whats', 'up'], ['cya'], ['See', 'you', 'later'], ['Goodbye'], ['I', 'am', 'Leaving'], ['Have', 'a', 'Good', 'day'], ['how', 'old'], ['how', 'old', 'is', 'tim'], ['what', 'is', 'your', 'age'], ['how', 'old', 'are', 'you'], ['age', '?'], ['what', 'is', 'your', 'name'], ['what', 'should', 'I', 'call', 'you'], ['whats', 'your', 'name', '?'], ['Id', 'like', 'to', 'buy', 'something'], ['whats', 'on', 'the', 'menu'], ['what', 'do', 'you', 'reccommend', '?'], ['could', 'i', 'get', 'something', 'to', 'eat'], ['when', 'are', 'you', 'guys', 'open'], ['what', 'are', 'your', 'hours'], ['hours', 'of', 'operation']]

#doc_tags (corresponding training data output)

['greeting', 'greeting', 'greeting', 'greeting', 'greeting', 'greeting', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'age', 'age', 'age', 'age', 'age', 'name', 'name', 'name', 'shop', 'shop', 'shop', 'shop', 'hours', 'hours', 'hours']

------------------------------------------
#pycharm
#translate data to machine

for n, doc in enumerate(docs_pattern):
    bag = []
    #clean input words
    wd_ = [stemmer.stem(w) for w in doc]
    #one hot encoding, training input, look through dictionary,
    # mark the words exist in user entry as 1, the rest 0
    for w in words:
        if w in wd_:
            bag.append(1)
        else:
            bag.append(0)

    output_ = out_empty[:]
    #the training output, mark 1 category, the rest 0
    output_[labels.index(docs_tag[n])] = 1

    training.append(bag)
    output.append(output_)

training = numpy.array(training)
output = numpy.array(output)
#print(training, output)

------------------------------------
#logs

#training (each row represent the AI dictionary, if word exists in input data, 1, else 0)

[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 1]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 1 0 1]
 [0 0 0 ... 0 1 0]
 [0 0 0 ... 0 0 0]]

#output (each input sentence belongs to 1 of the output categories)

[[0 0 1 0 0 0]
 [0 0 1 0 0 0]
 [0 0 1 0 0 0]
 [0 0 1 0 0 0]
 [0 0 1 0 0 0]
 [0 0 1 0 0 0]
 [0 1 0 0 0 0]
 [0 1 0 0 0 0]
 [0 1 0 0 0 0]
 [0 1 0 0 0 0]
 [0 1 0 0 0 0]
 [1 0 0 0 0 0]
 [1 0 0 0 0 0]
 [1 0 0 0 0 0]
 [1 0 0 0 0 0]
 [1 0 0 0 0 0]
 [0 0 0 0 1 0]
 [0 0 0 0 1 0]
 [0 0 0 0 1 0]
 [0 0 0 0 0 1]
 [0 0 0 0 0 1]
 [0 0 0 0 0 1]
 [0 0 0 0 0 1]
 [0 0 0 1 0 0]
 [0 0 0 1 0 0]
 [0 0 0 1 0 0]]

--------------------------------------------------
#pycharm
#train, generate model

tensorflow.reset_default_graph()
input AI dictionary 45 words
hidden layer 1 8 neuron
hidden layer 2 8 neuron
output 6 category. (softmax format [0.05,0.05,0.75,0.05,0.05,0.05] sum of all = 1)

#input shape
net = tflearn.input_data(shape=[None, len(training[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output[0]), activation='softmax')
net = tflearn.regression(net)

model = tflearn.DNN(net)
model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
model.save('model.tflearn')

--------------------------------------
#logs
#AI becomes intelligent after training

Training Step: 3997  | total loss: [1m [32m0.01108 [0m [0m | time: 0.001s
| Adam | epoch: 1000 | loss: 0.01108 - acc: 0.9999 -- iter: 08/26
[A [ATraining Step: 3998  | total loss: [1m [32m0.01098 [0m [0m | time: 0.002s
| Adam | epoch: 1000 | loss: 0.01098 - acc: 0.9999 -- iter: 16/26
[A [ATraining Step: 3999  | total loss: [1m [32m0.01092 [0m [0m | time: 0.003s
| Adam | epoch: 1000 | loss: 0.01092 - acc: 1.0000 -- iter: 24/26
[A [ATraining Step: 4000  | total loss: [1m [32m0.01149 [0m [0m | time: 0.004s
| Adam | epoch: 1000 | loss: 0.01149 - acc: 1.0000 -- iter: 26/26

-----------------------------------------
reference:

https://www.youtube.com/watch?v=wypVcNIH6D4&t=41s
https://www.youtube.com/watch?v=ON5pGUJDNow
https://www.youtube.com/watch?v=PzzHOvpqDYs

Friday 27 September 2019

Public Mobile

Public Mobile is a prepaid Canadian mobile cell phone phone provider founded in 2010 in Toronto, Ontario. Network: The Public Mobile network is provided by Telus which means you get LTE service anywhere Telus is available. Coverage: Public Mobile has got you covered on Canada's largest mobile network.

All plans include these features: Call Display, Voicemail and Conference Calling.

add-on

reference:

Monday 23 September 2019

django tensorflow

project urlhttps://chuanshuoge-movie-review.herokuapp.com/movie_review/
code linkhttps://github.com/chuanshuoge6/django-tensorflow-movieReview


fill in negative review, click predict

feed back is negative

paste in positive review, predict

prediction is positive

#movie_review/views

from django.shortcuts import render
from django.http import  HttpResponse
import tensorflow as td
from tensorflow import keras
import numpy as np

data = keras.datasets.imdb
#dictionary {word: index, word2, index2,...}
word_index = data.get_word_index()

def review_encode(s):
    #1 means 'start line'
    encoded = [1]

    for word in s:
         #translate human words to machine digits
        if word.lower() in word_index:
            encoded.append(word_index[word.lower()])
        else:
            #2 means 'word not found in dictionary'
            encoded.append(2)

    return encoded

def index(request):
    p = ''
    w = ''
    #model generated from machine learning
    model = keras.models.load_model('model.h5')
    # assume review is either negative or positive
    class_names = ['negative', 'positive']
    try:
        review_posted = request.POST['review']
    except Exception:
        pass
    else:
        nline = review_posted.replace(',', '').replace('(', '').replace(')', '').replace(':', '')\
            .replace("\"",'').strip().split(' ')
         #word -> digits
        encode = review_encode(nline)
        encode = keras.preprocessing.sequence.pad_sequences([encode], value=0, padding='post', maxlen=256)
        w = encode
        predict = model.predict(encode)
        print(review_posted)
        print(encode)
        result = class_names[int(round(predict[0][0]))]
        p = str(predict[0][0]) + ' ' + result
        print(predict[0], result)

    return render(request, 'index.html', {'prediction': p, 'wordMap': w})

--------------------------------------
#templates/index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Movie Review</title>
</head>
<body>
    <h2>Predict whether movie review is positive or negative</h2>

    <form action="{% url 'movie_review:index'  %}" method="post">
        {% csrf_token %}
        <label>Copy and paste movie review in English to the box below</label><br/>
        <textarea rows="8" cols="50" name='review'></textarea><br/>
        <input type="submit" value="Predict"><br/><br/>
    </form>

    <label>Prediction (0 = most negative, 1 = most positive)</label><br/>
    {{prediction}}<br/><br/>

    <label>AI word mapping, (AI dictionary contains 88584 vocabulary). extra long reviews will be trimmed for prediction</label><br/>
    {{wordMap}}
</body>
</html>

-----------------------------------
#django_keras/settings

TEMPLATES = [
    {
...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
    },
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR),
]

ALLOWED_HOSTS = ['chuanshuoge-movie-review.herokuapp.com', '127.0.0.1']

-------------------------------
#requirements

django==3.0a1
django-jsonview==1.2.0
django-watchman==0.18.0
tensorboard==1.14.0
tensorflow==1.14.0
tensorflow-estimator==1.14.0
numpy==1.16.4
numpydoc==0.9.1
astroid==2.1.0
autopep8==1.4.3
certifi==2019.6.16
chardet==3.0.4
colorama==0.4.1
defusedxml==0.6.0
gunicorn==19.9.0
idna==2.8
isort==4.3.4
lazy-object-proxy==1.3.1
mccabe==0.6.1
oauthlib==3.0.1
pycodestyle==2.4.0
pylint==2.2.2
python3-openid==3.1.0
pytz==2018.9
requests==2.22.0
requests-oauthlib==1.2.0
six==1.12.0
sqlparse==0.2.4
urllib3==1.25.3
wrapt==1.10.11
Keras==2.2.5
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.0
whitenoise==4.1.3

-----------------------------------
#Procfile

release: python manage.py migrate
web: gunicorn django_keras.wsgi

------------------------------------------
#powershell heroku

git init
heroku git:remote -a chuanshuoge-movie-review
heroku buildpacks:set heroku/python
pip install whitenoise gunicorn
git add .
git commit -am "make it better"
git push heroku master

-------------------------------
heroku logs

PS C:\Users\bob\django_keras> git add .
PS C:\Users\bob\django_keras> git commit -am "make it better"
[master 6101daa] make it better
 1 file changed, 3 insertions(+), 1 deletion(-)
PS C:\Users\bob\django_keras> git push heroku master
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 397 bytes | 397.00 KiB/s, done.
Total 4 (delta 3), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing requirements with pip
remote:
remote: -----> $ python manage.py collectstatic --noinput
remote:        Using TensorFlow backend.
remote:        158 static files copied to '/tmp/build_060c487a42affc8a12459384682ed518/staticfiles', 463 post-processed.
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> release, web
remote:
remote: -----> Compressing...
remote:        Done: 295.3M
remote: -----> Launching...
remote:  !     Release command declared: this new release will not be available until the command succeeds.
remote:        Released v6
remote:        https://chuanshuoge-movie-review.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
remote: Running release command...
remote:
remote: Using TensorFlow backend.
remote: Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb_word_index.json
remote: 1646592/1641221 [==============================] - 0s 0us/step
remote: Operations to perform:
remote:   Apply all migrations: admin, auth, contenttypes, sessions
remote: Running migrations:
remote:   No migrations to apply.
To https://git.heroku.com/chuanshuoge-movie-review.git
   084af5d..6101daa  master -> master

-------------------------------------
#powershell github
#delete .git first

git init
git add .
git commit -m '1'
git remote add origin https://github.com/chuanshuoge6/django-tensorflow-movieReview.git
git push -u origin master

------------------------------------
reference:
https://mc.ai/integrate-deep-learning-with-keras-in-django/
https://blog.slinto.sk/tensorflow-on-heroku-good-idea-3e6904105892
http://chuanshuoge2.blogspot.com/2019/09/neural-network-7.html

http://chuanshuoge2.blogspot.com/2019/03/django-13-form.html
http://chuanshuoge2.blogspot.com/2019/03/django-9-render-views.html
https://stackoverflow.com/questions/1926049/django-templatedoesnotexist

Sunday 22 September 2019

neural network 7

code linkhttps://github.com/chuanshuoge6/machineLearning-movieReview

#pycharm
#save model algorithm, so that don't have to create model everytime for a new prediction. Just load the model saved.

model.save('model.h5')

#add a txt file for testing

----------------------------
#test.py

import tensorflow as td
from tensorflow import keras
import numpy as np

data = keras.datasets.imdb

#word dictionary, format [{word, digit}...]
word_index = data.get_word_index()

def review_encode(s):
    #1 means 'start line'
    encoded = [1]

    for word in s:
         #translate human words to machine digits
        if word.lower() in word_index:
            encoded.append(word_index[word.lower()])
        else:
            #2 means 'word not found in dictionary'
            encoded.append(2)

    return encoded

#load model generated from machine training
model = keras.models.load_model('model.h5')

#assume review is either negative or positive
class_names = ['negative', 'positive']


with open('test.txt', encoding='utf-8') as f:

    for line in f.readlines():
        #dictionary does not contain symbols and punctuation, only pure english words
        nline = line.replace(',','').replace('(','').replace(')','').replace(':','').replace("\"",'').strip().split(' ')
        encode = review_encode(nline)
        #comply with the data format the model is trained in, 256 words a paragraphy, fill and trim to keep data shape
        encode = keras.preprocessing.sequence.pad_sequences([encode], value=0, padding='post', maxlen=256)
        predict = model.predict(encode)
        print(line)
        print(encode)
        #predict function input and output are lists, since input is a single paragraph, output[0] is the prediction. A prediction output is a list of numbers, this model only outputs 1 number - predict[0][0], value is between 0 and 1.
        print(predict[0], class_names[int(round(predict[0][0]))])

-------------------------------
#logs

If you're in desperate need of 90 minutes of gore-filled violence, Rambo: Last Blood will fill the order. Beyond that, there's nothing of value to be found here.

[[   1   45  332    8 1677  356    4 1549  231    4    2  564 3953  233
   538   77 2230    1    2  721   12  222  161    4 1104    5   27  255
     2    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0    0    0    0    0    0    0    0    0    0    0
     0    0    0    0]]
[0.34005865] negative
While Sylvester Stallone made the word Rambo synonymous with tough guy action in the 1980s, it's been a long time since he first made the character famous. In fact, it's been over a decade since the last Rambo movie, which itself came two decades before its predecessor. Culture, attitudes, and movies themselves have all changed a lot in that time. I'm not sure anybody was dying for another Rambo movie in 2019, and after having seen Rambo: Last Blood I'm still not sure exactly who this movie is for.

[[    1   134 13509  5808    90     1   678  3953 17261    16  1208   229
    203     8     1  3483    42    74     3   193    55   234    26    83
     90     1   106     2     8   189    42    74   117     3  2065   234
      1   233  3953    17    60   407   382   104  2737   156    91     2
   1178  4639     2    99   530    25    29  1191     3   173     8    12
      2   143    21   249  1811    13  1718    15   157  3953    17     8
  43837     2   100   257   107  3953   233   538   143   128    21   249
    615    34    11    17     6     2     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.13580143] negative
It's been 10 years since the events of Rambo, at the end of which, Vietnam War veteran John Rambo (Sylvester Stallone) returned to his family's home in Arizona. We learn as Rambo: Last Blood opens that while on the family ranch, he met Maria (Adriana Barraza) and her granddaughter Gabrielle (Yvette Monreal).

[[    1    42    74   155   150   234     1   684     4  3953    30     1
    127     4    60  2568   322  2493   305  3953 13509  5808  3779     5
     24  4715   341     8     2    72   847    14  3953   233   538  2010
     12   134    20     1   220  7030    26  1833  2904 28966     2     2
     38 12498 16931 21532     2     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.10586126] negative
The three of them have lived together on the Rambo ranch where John trains horses and he's become a surrogate father to Gabrielle. Rambo appears mostly at peace, though John's constructed a series of tunnels beneath the property where he keeps a pretty significant arsenal, because he is Rambo, after all.
[[    1     1   286     4    95    25  1449   292    20     1  3953  7030
    118   305  6897  3233     2   237   410     3  9817   333     5     2
   3953   736   666    30  2467   148  9279  4478     3   198     4 14157
   4155     1  4859   118    26   938     3   181  2678 19286    85    26
      6  3953   100     2     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.36746112] negative

-----------------------------------------------------
#copy and paste into test.txt positive reviews, run again
#logs

With its energy, its creativity, its raw passion and its fun, this film and its newcomer cast are the best thing I’ve seen at this year’s Toronto film festival.

[[    1    16    91  1705    91  4855    91  2818  1794     2    91   250
     11    19     2    91  6947   174    23     1   115   152 32871   107
     30    11     2  5879    19     2     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.71682703] positive
It’s a social-realist adventure written by Theresa Ikoko and Claire Wilson and directed by Sarah Gavron about a multi-ethnic community in East London - in the spirit of Ken Loach’s Kes or Céline Sciamma’s Bande Des Filles. It’s tough, but it’s the opposite of miserablist. At the story’s centre is a group of year 11 girls and the star is Bukky Bakray, playing a Nigerian British girl nicknamed “Rocks”, who is maybe no great academic high-flier but really talented at cosmetics. Her dad is dead and she lives with her troubled mum, who has had, as a social worker delicately puts it, issues managing her medication.

[[    1 21380     3     2  1151   395    31 12453     2     2  2891  2610
      2   523    31  2692     2    41     3     2  1827     8  2921  1313
      2     8     1  1100     4  3659     2 35070    39 38785     2     2
   6169     2 21380  1208    18 21380     1  1958     4     2    30     1
  57724  5923     6     3   601     4   288  1499   536     2     1   320
      6     2     2   392     3     2   695   247 21359     2    34     6
    276    54    84  9094     2    18    63  1017    30     2    38  1243
      6   348     2    56   453    16    38  3203  6997    34    44    66
     14     3  1028  3501 17247  1454     9  1338  8245    38     2     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.69423324] positive
It is Rocks who largely has the responsibility of minding her kid brother, Emmanuel, gloriously played by D’Angelou Osei Kissiedu – and Emmanuel is a black-belt scene-stealer. He starts the film the way he means to go on, with a hilarious setpiece. Asking if he may say grace before dinner, Emmanuel launches into his own version of the Lord’s Prayer: “Our father – he’s up in heaven.” Rocks cheerfully calls that his “remix”. But there’s real trouble when Rocks’s mum absents herself from the family home.

[[    1     9     6  3336    34  2253    44     1  4753     4 19316    38
    551   594 33274 12546   253    31     2     2     2  5047     2 33274
      6     3     2     2    26   514     1    19     1    93    26   814
      5   137    20    16     3   639     2  2251    45    26   200   132
   1695   156  3065 33274 20969    80    24   202   307     4     1     2
  11467     2   333  5047 36347    53     8     2  3336 17321  2015    12
     24     2    18 35733   144  1110    51     2  6997     2   762    36
      1   220     2     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.7644717] positive
The odyssey of Rocks and Emmanuel – who in effect go on the run, fugitives from the world of grownup authority – provides a motor that drives the film but, in a way, its best moments come when Rocks and her friends are doing nothing more dramatically significant than just hanging out, talking and laughing. Occasionally these scenes erupt into something defiant, as when a food fight monumentally kicks off in the middle of a home economics class or when a girl tells her grumpy teacher: “You’re like this because you’ve got your period, sir.” (He furiously replies: “That’s actually really offensive.”)

[[    1     1  6758     4  3336     2 33274  5047    34     8   959   137
     20     1   518 32018    36     1   179     4 79917  4262  5047  1565
      3 11035    12  3041     1    19    18     8     3    93    91   115
    385   213    51  3336     2    38   366    23   396   161    50  6728
   2678    71    40  2345    43   659     2     2  2033   131   136 21687
     80   139 16633    14    51     3  1641   545 22736  3412   122     8
      1   652     4     3   341 21005   704    39    51     3   247   713
     38  9739  1747     2    37    11    85     2   185   126   807     2
     26 33322  7228     2   162    63     2     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.64768946] positive
But really, the improv-type dialogue doesn’t need to go anywhere or do anything to be hugely entertaining and watchable. The group around Rocks are capable, in the best possible way, of laughing about nothing, laughing from sheer directionless joy. The sadness, when it comes, is piercing – yet so is Rocks’s resilience and her philosophical acceptance. Bukky Bakray gives a very moving portrayal of someone who has boldly accepted maternal responsibility for Emmanuel at the very moment that she is to be deprived of it.

[[    1    18    63     1     2   411 40881   356     5   137  1761    39
     78   230     5    27  6121   438     2     2     1   601   184  3336
     23  2247     8     1   115   611    93     4  1101    41   161  1101
     36  2096 26625     2     1  3904    51     9   263     6 12315  5047
    243    35     6     2 26408     2    38  4342     2     2     2   405
      3    52   725  1143     4   291    34    44 15145  3208 32086  4753
     15 33274    30     1    52   558    12    56     6     5    27 14224
      4     2     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.63985294] positive
Of course, there is a larger sadness here: the realisation that the sheer energy and dynamism of this group is likely to be dissipated and wasted when they leave school – society will probably not find a way to tap this resource. When the class is taught about Picasso and cubism and they make spoof Picasso cut-out images of people’s faces cut from magazines, it is a funny moment, but serious too, because there is a real sense of potential. This film is such a rush of vitality. It rocks.
[[    1     4   262    47     6     3  3220  3904   130     1 17640    12
      1  2096  1705     2 35071     4    11   601     6  1326     5    27
  31510     2  1050    51    33   560   393  5047   923    77   239    21
    166     3    93     5  3929    11     2    51     1   704     6  4456
     41 21141     2     2     2    33    94  2835 21141     2  1215     4
      2  1587   602    36  8257     9     6     3   160   558    18   619
     96    85    47     6     3   144   278     4     2    11    19     6
    138     3  3406     4     2     9     2     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0     0     0     0     0     0     0     0     0
      0     0     0     0]]
[0.6369015] positive

----------------------------------
reference:
http://chuanshuoge2.blogspot.com/2019/09/neural-network-6.html
https://www.youtube.com/watch?v=Xmga_snTFBs&list=PLzMcBGfZo4-lak7tiFDec5_ZMItiIIfmj&index=8

Friday 20 September 2019

neural network 6

good and bad reviews are transformed into vectors. Their angles are far apart.



all layers

#pycharm
#input layer - dictionary has 10000 words, 16 coefficients for vectors model (ax + by + cz...)
#output layer - between 0 and 1

model = keras.Sequential()
model.add(keras.layers.Embedding(10000, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(1, activation='sigmoid'))

#model.summary()

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

#dataset has 25000 reviews, use 10000 for training, and rest for testing
x_val = train_data[:10000]
x_train = train_data[10000:]

y_val = train_labels[:10000]
y_train = train_labels[10000:]

fitmodel = model.fit(x_train, y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val), verbose=1)

result = model.evaluate(test_data, test_labels)

print(result)

prediction = model.predict(test_data)

for i in range(10):
    print('predicted: ', prediction[i], ' actural: ', test_labels[i])

--------------------------------------
#logs
#model accuracy for training and testing data are different

Epoch 20/20

  512/15000 [>.............................] - ETA: 0s - loss: 0.2149 - acc: 0.9180
 2048/15000 [===>..........................] - ETA: 0s - loss: 0.2155 - acc: 0.9243
 3584/15000 [======>.......................] - ETA: 0s - loss: 0.2150 - acc: 0.9241
 5120/15000 [=========>....................] - ETA: 0s - loss: 0.2174 - acc: 0.9209
 6656/15000 [============>.................] - ETA: 0s - loss: 0.2149 - acc: 0.9229
 8192/15000 [===============>..............] - ETA: 0s - loss: 0.2134 - acc: 0.9249
 9216/15000 [=================>............] - ETA: 0s - loss: 0.2102 - acc: 0.9271
10240/15000 [===================>..........] - ETA: 0s - loss: 0.2115 - acc: 0.9265
11776/15000 [======================>.......] - ETA: 0s - loss: 0.2123 - acc: 0.9260
13312/15000 [=========================>....] - ETA: 0s - loss: 0.2136 - acc: 0.9259
14848/15000 [============================>.] - ETA: 0s - loss: 0.2126 - acc: 0.9261
15000/15000 [==============================] - 1s 50us/sample - loss: 0.2122 - acc: 0.9264 - val_loss: 0.2958 - val_acc: 0.8809

   32/25000 [..............................] - ETA: 0s - loss: 0.2635 - acc: 0.9375
 3808/25000 [===>..........................] - ETA: 0s - loss: 0.3024 - acc: 0.8789
 7744/25000 [========>.....................] - ETA: 0s - loss: 0.3043 - acc: 0.8759
11488/25000 [============>.................] - ETA: 0s - loss: 0.3122 - acc: 0.8718
15264/25000 [=================>............] - ETA: 0s - loss: 0.3109 - acc: 0.8726
19072/25000 [=====================>........] - ETA: 0s - loss: 0.3068 - acc: 0.8752
23040/25000 [==========================>...] - ETA: 0s - loss: 0.3087 - acc: 0.8738
25000/25000 [==============================] - 0s 13us/sample - loss: 0.3084 - acc: 0.8740
[0.308388222618103, 0.87404]
predicted:  [0.255415]  actural:  0
predicted:  [0.99322104]  actural:  1
predicted:  [0.68470025]  actural:  1
predicted:  [0.4331221]  actural:  0
predicted:  [0.96165186]  actural:  1
predicted:  [0.64715904]  actural:  1
predicted:  [0.9213904]  actural:  1
predicted:  [0.20285302]  actural:  0
predicted:  [0.93451846]  actural:  0
predicted:  [0.9832784]  actural:  1

---------------------------------------
reference:
http://chuanshuoge2.blogspot.com/2019/09/neural-network-5.html
https://www.youtube.com/watch?v=qpb_39IjZA0&list=PLzMcBGfZo4-lak7tiFDec5_ZMItiIIfmj&index=6

Wednesday 18 September 2019

neural network 5

#pycharm
#dataset contains lots of movie reviews, all of which are coded in a list of digits. There is a dictionary to translate those reviews to human readable words. 
#goal is to predict whether reviews are positive or negative

import tensorflow as td
from tensorflow import keras
import numpy as np

data = keras.datasets.imdb

(train_data, train_labels),(test_data, test_labes) = data.load_data(num_words=10000)

print(train_data[0])

--------------------------------------------
#logs

[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50...]

----------------------------------------
#pycharm
#look up dictionary to translate digits into words. define 0 means padding, 1 means start... 

word_index = data.get_word_index()

word_index = {k:(v+3) for k, v in word_index.items()}
word_index['<padding>']=0
word_index['<start>']=1
word_index['<unknown>']=2
word_index['<unused>']=3

reverse_word_index = dict([(value,key) for (key, value) in word_index.items()])

def decode_review(text):
    return ' '.join([reverse_word_index.get(i,'?') for i in text])

print(decode_review(test_data[0]))

-----------------------------------------
#logs

<start> please give this one a miss br br <unknown> <unknown> and the rest of the cast rendered terrible performances the show is flat flat flat br br i don't know how michael madison could have allowed this one on his plate he almost seemed to know this wasn't going to work ...

----------------------------------
#pycharm
#check word count of each review

print(len(test_data[0]), len(test_data[1]))

---------------------------
#logs
#review length are different

68 260

--------------------------------
#pycharm
#normalize reviews, set max word count 250, less than which, fill at end <padding>, more than that, truncate
...
reverse_word_index = dict([(value,key) for (key, value) in word_index.items()])

train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=0, padding='post', maxlen=250)
test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=0, padding='post', maxlen=250)

def decode_review(text):
    return ' '.join([reverse_word_index.get(i,'?') for i in text])
...
-------------------------------------------
#logs
#review 1 filled with padding, reivew 2 truncated, both size are 250 now

...you madison fans give this a miss <padding> <padding> <padding> <padding> ...

250 250

--------------------
reference:

https://www.youtube.com/watch?v=k-_pWoy2fb4&list=PLzMcBGfZo4-lak7tiFDec5_ZMItiIIfmj&index=5
https://www.tensorflow.org/tutorials/keras/basic_text_classification

Tuesday 17 September 2019

neural network 4

#pycharm
#print output neurons of the first prediction which are the probability of each of the 10 categories

prediction = model.predict(test_images)
print(prediction[0])

--------------------------------------
#logs
#the last category is what AI thinks the category that the wear most likely belongs to

[3.4543206e-07 1.4980142e-09 1.3186813e-07 2.5887127e-08 1.9471056e-08
 4.6815544e-02 1.1219876e-05 1.2661220e-02 9.5906926e-06 9.4050187e-01]

------------------------------------------------------------------
#pycharm
#print the first 5 test images with the actual category and the category that AI thinks most likely

for i in range(5):
    plt.grid(False)
    plt.imshow(test_images[i], cmap=plt.cm.binary)
    plt.xlabel('actual: ' + class_names[test_labels[i]])
    plt.title('prediction: ' + class_names[np.argmax(prediction[i])])
    plt.show()

-------------------------------
#matplotlib
#AI guessed all right, images make sense to be in the predicted category







reference:
http://chuanshuoge2.blogspot.com/2019/09/neural-network-3.html
https://www.youtube.com/watch?v=RqLD1INA_cQ