Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,241 members, 7,807,818 topics. Date: Wednesday, 24 April 2024 at 07:48 PM

Gbolly1151's Posts

Nairaland Forum / Gbolly1151's Profile / Gbolly1151's Posts

(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (of 16 pages)

Programming / Re: Common good python programming practices you should know by gbolly1151(m): 7:02pm On May 24, 2020
HOW TO USE LAMBDA

The format of lambda is as below

[lambda keyword] [arguments[seperated by comma]] [semicolon] [logic]


e.g
# with single argument
lambda x: x*x

#multiple argument
lambda x,y: x*y

now assign that with variable name

mul=lambda x,y:x*y

x=5
y=6
print(mul(x,y))

#output 30
Programming / Re: Python 3: Exercises And Solutions. by gbolly1151(m): 4:40pm On May 24, 2020
Reserve
Programming / Re: Python 3: Exercises And Solutions. by gbolly1151(m): 3:29pm On May 24, 2020
SKYQUEST:


can you read this as CSV, will it work?, methinks the file is not comma separated file.

I think read_csv take optional argument delimiter which can be comma,using spaxe should work
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 9:39pm On May 22, 2020
iCode2:
Hi gbolly1151, you seem to be very good with Python. When did you start learning? And are you self-taught?
I started learning python few years ago and am a self-taught
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 3:43pm On May 22, 2020
HOW TO SWAP AN OBJECT

a,b = 4,7
print(a,b) #output : 4,7
a,b=b,a
print(a,b) #output: 7,4
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 2:32pm On May 22, 2020
REMINDER: Range has step argument

range(start,stop,step)

Note that start and step are optional

How to use step in range to print odd and even

for even in range(2,10,2):
print(even)

#output : 2,4,6,8

for odd in range(3,10,2):
print(odd)

#output: 3,5,7,9
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 12:05pm On May 22, 2020
What is activation?
Here is the flow from input to output

(Input(x) >>>> sum(a+bx) >>>> activate >>>> output)

Every perceptron has activation,by default activation is
1 if (a+bx) >= 0 and
0 if (a+bx) < 0

Activation is what help to transform the result of
(a+bx),they take a+bx as input inside a perceptron. This is needed to reach our desire output Y in fast manner.

So let z=a+bx

We have various type of activation,some are;
1.relu: The rectified linear unit function, returns f(z) = max(0, z).
2.logistic: The logistic sigmoid function, returns f(z) = 1 / (1 + exp(-z)).
3.identity: No-op activation, useful to implement linear bottleneck, returns f(z) = z
4. tanh: The hyperbolic tan function, returns f(z) = tanh(z).


Let update our code


from math import exp as e,tanh as t
from random import randint

def sigmoid (z):
return 1/(1+e(-z))

def relu(z):
return max(0,z)

def tanh(z):
return t(z)

def perceptron(input_set:list,activation=None):
a,b=round(randint(1,4)/5,3),[round(randint(1,4)/5,3) for i in range(len(input_set))]
bx=0
for weight,x in zip(b,input_set):
bx+=weight*x
z=a + bx
if activation is None:
return 1 if z >= 0 else 0
return activation(z)

#Let test our output
output=perceptron([1,0],activation=tanh)
print(output) # mine print 1
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 5:08pm On May 21, 2020
scarplanet:


Negative. Try again grin grin
Hmm....ikena boss
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 2:54am On May 21, 2020
faithfull18:
Hmmn. How does one learn all these maths embarassed
Pick up your o or A level textbook they are there, linear algebra
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 10:40pm On May 20, 2020
What is perceptron?
Perceptron is the simplest network that accept input(x) or inputs(X1....Xn), multiplying the input by weight (b) making it (bx),adding bias (a) to it,then activating the function (a + bx) using various activation function like sigmiod to produce predicted output(YP).

by default activation is
1 if (a+bx) >= 0 and
0 if (a+bx) < 0

Here is the flow

Input(x) >>>> sum(a+bx)>>>> activate >>>>output


def Perception(input,weight=0.4,bias=0.1): #only one input for now
x,b,a=input,weight, bias
z=a + bx
return 1 if z >= 0 else 0

Yp= Perceptron(1)


Activation function is what help to produce predicted output(YP) that is closer to Y.

Sigmoid function is sigmiod(z) = 1/1+e^-z ,it is one of activation function

In real world input(x) are more that 1 e.g
Input1 = [0,1,0,1] output=1
input2= [1,1,0,1] output = 0

In this case
Y= a + b1.x1 + b2.x2 + b3.x3 + b4.x4

1 Like

Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 10:08pm On May 20, 2020
scarplanet:


Nice one Tag wink wink
Hmm...praise?
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 7:39pm On May 20, 2020
iCode2:
This looks like Physics. cheesy
Hmm...it is possible to see that equation in physics but it is math [linear equation]
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 4:33pm On May 20, 2020
How to create a simple singleton without decorator

Decorator is one of the popular way of creating singleton in python but we wont be using decorator here. before i move to code let me define singleton,it is a way of creating a single object of a class or function. In a program where you only need a single instance of a class you can create a Singleton.


class Test:
def __init__(self):
self.num=5
def fmethod (self,mynum):
mynum *=2
return 'fmethod mynum is {0}'.format(mynum)

def singleton(func,*args,**kwargs):
obj=globals()['__cached__']
if obj is None:
globals()['__cached__']=func(*args,**kwargs)
obj=globals()['__cached__']
return obj

Testobj1=singleton(Test)
Testobj2=singleton(Test)

print(Testobj1 == Testobj2)
# output : True

Testobj1.num=10
print(Testobj2.num)
#output : 10
Programming / Re: Let Learn Artificial Neutral Network by gbolly1151(m): 12:36pm On May 20, 2020
The backbone or foundation of deep learning is from this equation below


Y=a+bx

what ANN is looking for is a and b

A typical question to throw to the network is if Y= 1 and X=0 find a and b

How ANN find a and b is as follows
1. first get random value for a and b
2. Calculate Y from x using a and b generated (a + bx)
3. If output is not equal to Y,update a and b and try again

On a norm we can do this by bruce-force method but it consume a lot of time and resources to find the real a and b

How ANN minimize the error is by calculating a and b from the error obtain using gradient decent

Error= Y - YP (YP = output gotten from random pick for a and b]

This error is used to update our a and b by finding the rate at which a and b has contributed to the error i.e dE/db and dE/da

Our new a and b for next testing will

a=a + dE/da
b=b + dE/db

in order to speed up our findings we add step called learning rate n

So new equation is

a= a + n dE/da
b=b + n dE/db

we will continue updating still we find the real a and b that satisfy the equation.
Programming / Let Learn Artificial Neutral Network by gbolly1151(m): 3:09am On May 20, 2020
In the last few weeks now,i embarked on ANN journey and it has been fun and exciting to learn. I will like to open this thread for people to drop what will be helpful for beginner as we journey in this ANN together.

1 Like

Programming / Re: Common good python programming practices you should know by gbolly1151(m): 9:27pm On May 19, 2020
DanRay1:
How does this code repeatedly prompt the user for input when the input line isn't in the while loop block? Or is it in the collatz function? Because it doesn't look like you put it there. If it's in the function, then indent it a bit to make it readable and clearer.

def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1


If __name__=='__main__':
number =int(input("Enter Number" ))
Num = number
while Num != 1:
Num=collatz(Num)
print(Num)


Hope it is readable?

1 Like 1 Share

Programming / Re: Common good python programming practices you should know by gbolly1151(m): 9:13pm On May 19, 2020
DanRay1:
How does this code repeatedly prompt the user for input when the input line isn't in the while loop block? Or is it in the collatz function? Because it doesn't look like you put it there. If it's in the function, then indent it a bit to make it readable and clearer.
We are only required to input a number then it will print out all the collatz number still 1

1 Like

Programming / Re: Common good python programming practices you should know by gbolly1151(m): 8:30pm On May 18, 2020
iCode2:
Can anyone recommend good python books with a lot of exercises? I just started out with automate the boring stuff.
Download think python
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 7:05pm On May 18, 2020
Predstan:


Ok, But on the other hand, look at this bolded part of the question. I was thinking, we should be checking that return value is not equal to 1 and not our input value


Have you tried to run the code and it works as you expected?
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 5:04pm On May 18, 2020
Or there is something i don't get?
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 4:44pm On May 18, 2020
Predstan:


First you need to return the number from the Collatz function as an integer not a print function... use: return number//2.

Then you have to check that the return value from the Collatz is not equal to 1 if not, user keeps inputting number and the Collatz function is called on the number from user.


def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1

number =int(input("Enter Number" ))
Num = collatz(number)
while Num != 1:
continue




Using Recursion:

def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
def main():

number =int(input("Enter Number" ))
Num = collatz(number)
while Num != 1:
main()
return print ("Callatz on", number, "is", Num)

main()


That code for recursion doesn't look like one and even the first method will still end up looping and wont end.
Am thinking should look like this


def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1

number =int(input("Enter Number" ))
Num = number
while Num != 1:
Num=collatz(Num)
print(Num)
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 1:41pm On May 16, 2020
Predstan:


I finally learnt OOP. I have completed a project. Its coordinate of a line with slope, distance and to determine if a line is vertical or horizontal and if it is perpendicular or parallel to another.

I also completed a Time project to display the julian day, the day of the week, of that date and gregorian date. Its interesting so far. I couldn't display the calendar without the normal calendar module. I am trying to create my own calendar module but I didnt get that.

I'm also currently working on Polygon.


Nice one bro...keep it up
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 11:07am On May 16, 2020
WHAT IS if __name__=='__main__'?

#short explanation

if __name__=='__main__':
print('hello')

then, you are telling the computer that if this python file is run by user or robot then
print('hello')


#full explanation
Anytime you open python file,you are actually loading the
file into the memory of the computer (i.e RAM). The name
that will be given to that file at that point wont be the
name of the file but a new name that is called
'__main__' (i.e __name__='__main__') and it is stored together with other data in
memory.

To check that, open any python file and print global data
using global keyword


print(globals())

output
...
{'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py',
'__package__': None, '__cached__': None,
'__name__': '__main__', '__doc__': None}


from that output above we can see that __name__= '__main__'

so at runtime the name of any python file is '__main__'.

This name is often use proffessionally in python for testing or running the
functionality of a script at runtime.

you might be wondering why we have underscore,This is because
we dont want it to be in conflict when we use 'name' as variable name in our program

now,if you use

if __name__=='__main__':
print('hello')

then, you are telling the computer that if this python file is run by user or robot then
print('hello')

you can acqually change the variable of __name__

e.g

__name__='changed'

#now let see the changed name of the file at runtime
print(globals())

#output
{'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py',
'__package__': None, '__cached__': None,
'__name__': 'changed', '__doc__': None}

we can see that our __name__ has been assign another variable

Programming / Re: Common good python programming practices you should know by gbolly1151(m): 9:13am On May 14, 2020
HOW TO USE all() KEYWORD

all() in python is a keyword that take iterable object
as aguement and return true only when all the elements in
this iterable are true '''


#Example 1
string=[True,False,True]
print(all(string))

#output: False
string=[True,True,True]
print(all(string))

#output:True

'''
Example 2
let say you want to validate user input from unknown source
'''
required_field=['name','age','score']
user_value={'name':'peter','age':20,'score':300}

#native aproach
#note that this only check for key and not value itself
#but you can cook it to your taste

def is_valid(require,value):
for field in required_field:
if field not in user_value.keys():
return False
return True

print(is_valid(required_field,user_value))

#output: True
#if you change the key,it will be false on run

#pythonic approch

print(all([field in user_value.keys() for field in required_field]))

#output:True
#if you change the key in user_field it will turn False on run
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 3:02pm On May 11, 2020
Brukx:
Bro, can you recommend any good kivy book?
I haven't try building mobile app before so don't know the best book out there but you can search for kivy tutorial on Google the first index still look ok
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 7:30am On May 11, 2020
ALWAYS USE .startswith() AND .endwith() FOR SLICING OF STRING
To aviod hardcoding of number into your code avoid the use of
slicing in your code and to compliance with PEP8

E.g to check if string "younger" start with 'you' use

word="younger"
if word.startswith('you'):
#do something
pass

#avoid this
if word[:3] == 'you':
#do something
pass
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 4:51am On May 11, 2020
Antiausen:
Good thread cool
Thanks sir
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 4:50am On May 11, 2020
Hotspotbro:
kivy on Pydroid
Can you just give me a sample code?

from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):
def build(self):
# display a button with the text : Hello QPython
return Button(text='Hello QPython')

TestApp().run()


Note that there is a documentation on how you can allow it to work on Andriod device

Go to google and search for kviy tutorial pdf or video to see how to compile your kivy python file to work with android,there are 2 or 3 ways to do that,you can pick the anyone you can easily grab
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 3:17pm On May 10, 2020
Hotspotbro:
Pls i want to know if there is a Android game package based on python.
To build android app with python use kivy
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 11:49am On May 10, 2020
Predstan:


Finally learnt OOP on LinkedIn learning (lynda)

I got some Covid-19 data for every countries and I will be visualizing some stuffs.

Nice one bro
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 9:43am On May 10, 2020
IF YOU ARE CONFUSED ABOUT WHILE LOOP CHECK THIS OUT

n=True
while n==True:
print('hello')

it means you are telling the computer that as long as n value isTrue(n=True) continue printing 'hello' for me

Hope you can take it from there
Programming / Re: Common good python programming practices you should know by gbolly1151(m): 8:07pm On May 09, 2020
gbolly1151:

HOW TO USE GLOBALS() AND LOCALS() FUNCTION
In programming we have two types of variable namely:
1. Global variable
2. Local variable

Before we dive into those two varibles,you need to understand
that all your variable name and value in python are stored
in a dict data structure e.g


value=1
Good=True

the way python present this is,

{'value':1,'Good':True}


#Then how can we checked this structure? just use
print(globals())

output will be

{'__builtins__': <module 'builtins' (built-in)>,
'__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py',
'value': 1,'Good':True '__package__': None,
'__cached__': None, '__name__': '__main__', '__doc__': None}

you can see that your variables are stored in dict structure
'value':1 and 'Good':True

To get value use

print(globals()['value'])
output
1

for now dont mind other variables you saw in the global scope,they are needed for your program to work well

All variable that can be obtained through globals() are called global variable.These are variables that are in
__main__ i.e global enviroment of the program

Now let talk about local variable....

All variable you create after indentation,they are all
local variable example of structure that use indentation are
function,class,with ,if else et.c . Let check this;


def increment():
fund=36
return True


variable name 'fund' is written after an indentation,which is
local variable of increment function,this means only increment
has the power to perform operation on fund . To check and
print the local variable just use keyword locals() and
all local variable will be displayed


def increment():
fund=36
return locals()

print(increment())

output

{'fund': 36}


Let take a break from here and continue with global and nonlocal keyword later
Alteratively, you can use vars() to get your key and data

(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (of 16 pages)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 76
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.