repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Dicionários em Python/python_076.py
|
<filename>Python_Exercicios/Mundo3/Dicionários em Python/python_076.py<gh_stars>0
'''
Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas
B) A média de idade
C) Uma lista com as mulheres
D) Uma lista de pessoas com idade acima da média
'''
# Criar uma lista para colocar todas as pessoas cadastradas
galera = list()
# Criar um dicionário para cadastro de pessoa
pessoa = dict()
soma = media = 0
while True:
# Para vir uma pessoa nova
pessoa.clear()
# Fazer cadastro através do teclado
pessoa['nome'] = str(input('Nome: '))
# Fazer um laço while para que só aceite M ou F para sexo
while True:
pessoa['sexo'] = str(input('Sexo: [M/F] ')).upper()[0]
if pessoa['sexo'] in 'MF':
break
print('ERRO! Por favor, digite apenas M ou F.')
pessoa['idade'] = int(input('Idade:'))
soma += pessoa['idade']
galera.append(pessoa.copy())
while True:
resp = str(input('Quer continuar? [S/N] ')).upper()[0]
if resp in 'SN':
break
print('ERRO! Responda apenas S ou N.')
if resp == 'S':
break
print('-=' * 30)
print(f'Ao todo temos {len(galera)} pessoas cadastradas.')
media = soma / len(galera)
print(f'A média de idade é de {media:5.2f} anos.')
print('As mulheres cadastradas foram: ', end='')
for p in galera:
if p['sexo'] == 'F':
print(f'{p["nome"]} ', end='')
print()
print('Lista das pessoas que estão acima da média: ')
for p in galera:
if p['idade'] >= media:
print(' ')
for k, v in p.items():
print(f'{k} = {v}; ', end = '')
print()
print('<< ENCERRADO >>')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_041.py
|
<filename>Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_041.py
'''
Crie um programa que faça o computador jogar Jokenpô com você.
'''
# Para o computador escolher uma string
from random import randint
# Esperando 1 segundo dizendo Jokenpo
from time import sleep
# Ler uma palavra
print('[1] PEDRA: ')
print('[2] PAPEL: ')
print('[3] TESOURA: ')
usuario = int(input('Escolha: '))
if usuario == 1:
usuario = 'PEDRA'
elif usuario == 2:
usuario = 'PAPEL'
elif usuario == 3:
usuario = 'TESOURA'
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
sleep(1)
# O computador escolherá uma palavra aleatoriamente
escolha = randint(1, 3)
if escolha == 1:
escolha = 'PEDRA'
elif escolha == 2:
escolha = 'PAPEL'
elif escolha == 3:
escolha = 'TESOURA'
# Jogando com o computador
print('A escolha do usuário foi {} e a escolha do computador foi {}.'.format(usuario, escolha))
usuario_vencedor = (usuario == 'PEDRA' and escolha == 'TESOURA') or (usuario == 'PAPEL' and escolha == 'PEDRA') or (usuario == 'TESOURA' and escolha == 'PAPEL')
empate = usuario == escolha
print()
print('-=='*10)
if empate:
print('O JOGO EMPATOU!')
elif usuario_vencedor:
print('O jogador VENCEU!!!')
else:
print('O computador VENCEU!!!')
print('-=='*10)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula15.py
|
n = s = 0
while True:
n = int(input('Digite um numero: '))
if n == 999:
break
s += n
# Usando f string para formatar o print
print(f'A soma vale {s:.2f}.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_015.py
|
'''
Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por km rodada.
'''
# Leia
dias = int(input('Quantos dias alugados? '))
km = float(input('Quantos km rodados? '))
# Calculo
pago = (dias * 60) + (km * 0.15)
# Imprimir na tela
print('O total a pagar é de R${:.2f}.'.format(pago))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_027.py
|
'''
Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último separadamente.
'''
# Leia o nome de uma pessoa
n = str(input('Escreva o nome: ')).strip()
# Separar o nome em partes
nome = n.split()
# Imprimir
print(n)
print('O seu primeiro nome é {}.'.format(nome[0]))
print('O seu último nome é {}.'.format(nome[len(nome) - 1]))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_036.py
|
<filename>Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_036.py<gh_stars>0
'''
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
'''
# Ler os valores da casa e do salário
valor_casa = float(input('Qual o valor da casa? R$'))
salario = float(input('Qual o valor do seu salário? R$'))
tempo_de_pagamento = int(input('Em quantos anos pretende pagar? '))
# Calcular o valor da parcela
parcela = (valor_casa / tempo_de_pagamento) / 12
# Calcular o percentual do salario
percentual_salario = int((parcela * 100) / salario)
# Uso de operações Relacionais
emprestimo_autorizado = percentual_salario < 30
emprestimo_autorizado_limite = percentual_salario == 30
print('$$'*40)
print()
# Estrutua Condicional if, elif e else
if emprestimo_autorizado:
print('PARABÉNS! O seu empréstimo foi autorizado com sucesso.')
print('A sua parcela por mês será de {:.2f}, o pagamento será concluido em {} anos.'.format(parcela, tempo_de_pagamento))
elif emprestimo_autorizado_limite:
print('PARABÉNS! O seu empréstimo foi autorizado, mas cuidado pois está no limite de 30% do seu salário.')
print('A sua parcela por mês será de {:.2f}, o pagamento será concluido em {} anos.'.format(parcela, tempo_de_pagamento))
else:
print('O seu empréstimo foi negado, pois o valor da parcela ultrapassa 30% do seu salário.')
print()
print('$$'*40)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_004.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
n = input('Digite algo: ')
print('O tipo primitivo é: ',type(n))
print('É alfabético? ',n.isalpha())
print('É numérico? ',n.isnumeric())
print('É alphanumérico? ',n.isalnum())
print('É tudo maiusculo? ',n.isupper())
print('É tudo minusculo? ',n.islower())
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula08a.py
|
<gh_stars>0
from math import sqrt, ceil
num = int(input('Digite um número: '))
raiz = sqrt(num)
print('A raiz de {} é igual a {}.'.format(num, ceil(raiz)))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_011.py
|
<filename>Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_011.py
'''
Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária pra pintá-la, sabendo que cada litro de tinta, pinta uma área de 2 metros quadrados.
'''
#Ler largura e altura
l = float(input('Digite a largura: '))
a = float(input('Digite a altura: '))
# Calcular a área
area = l * a
# Calcular a quantidade de tinta
t = area / 2
# Imprimir na Tela
print('A largura é {:.2f}.'.format(l))
print('A altura é {:.2f}.'.format(a))
print('A área é {:.2f}.'.format(area))
print('A quantidade de tinta usada é {:.2f} litros.'.format(t))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_009.py
|
<filename>Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_009.py
'''
Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
'''
# Leia um número Inteiro
n = int(input('Digite um número Inteiro: '))
# Tabuada
t1 = n * 1
t2 = n * 2
t3 = n * 3
t4 = n * 4
t5 = n * 5
t6 = n * 6
t7 = n * 7
t8 = n * 8
t9 = n * 9
t10 = n * 10
# Imprimir na tela
print('Tabuada de {} é: '.format(n))
print('{} x 1 = {}'.format(n, t1))
print('{} x 2 = {}'.format(n, t2))
print('{} x 3 = {}'.format(n, t3))
print('{} x 4 = {}'.format(n, t4))
print('{} x 5 = {}'.format(n, t5))
print('{} x 6 = {}'.format(n, t6))
print('{} x 7 = {}'.format(n, t7))
print('{} x 8 = {}'.format(n, t8))
print('{} x 9 = {}'.format(n, t9))
print('{} x 10 = {}'.format(n, t10))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Dicionários em Python/python_073.py
|
'''
Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário em Python. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.
'''
# Importar randint de random para pegar numeros aleatórios. E importar sllep de time para esperar um tempo de um jogador para outro. Importar itemgetter para organizar o ranking.
from random import randint
from time import sleep
from operator import itemgetter
# Criar um dicionário chamado jogo
jogo = {'jogador1': randint(1, 6),
'jogador2': randint(1, 6),
'jogador3': randint(1, 6),
'jogador4': randint(1, 6)}
# Criar um dicionario para rankear os jogadores.
ranking = list()
print('Valores sorteados:')
# Para formatar um print usando for
for k, v in jogo.items():
print(f'{k} tirou {v} no dado.')
sleep(2)
ranking = sorted(jogo.items(), key=itemgetter(1), reverse = True)
print('-=' * 30)
print(' === Ranking dos Jogadores ===')
for i, v in enumerate(ranking):
print(f' {i+1}º lugar: {v[0]} com {v[1]}.')
sleep(2)
#
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_008.py
|
'''
Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e melimetros.
'''
# Leia um valor em metros
m = float(input('Digite um valor em metros: '))
# Converter para centimetros
c = float(m * 100)
# Converter para milimetros
mm = float(m * 1000)
# Imprimir na tela
print('{:.1f}m'.format(m))
print('{:.1f}cm'.format(c))
print('{:.1f}mm'.format(mm))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_066.py
|
'''
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente.
C) Se o valor 5 foi digitado e está ou não na lista.
'''
# Aplicar uma lista
numeros = list()
contador = 0
# Aplicar um laço while que enquanto for verdadeiro pedir para o usuário digitar um número
while True:
n = int(input('Digite um número: '))
numeros.append(n)
contador += 1
r = str(input('Deseja continuar? Digite S para continuar ou N para parar: '))
if r in 'Nn':
break
# Fazer a ordem decrescente
numeros.sort(reverse=True)
print(f'A quantidade de números digitados foi {contador}')
print(f'A ordem descrecente é {numeros}')
# Para saber se o número 5 está na lista
if 5 in numeros:
print('O número 5 está na lista')
else:
print('O número 5 não está na lista')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_012.py
|
'''
Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
'''
# Ler o preço de um produto
preco = float(input('Qual é o preço do produto? R$ '))
# novo preço com desconto
novo = preco - (preco * 5 / 100)
# Imprimir na tela
print('O preço que custava R${}, na promoção vai custar R${}.'.format(preco, novo))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_034.py
|
'''
Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250.00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
'''
# Ler salário
salario = float(input('Informe o salário: R$'))
print('O atual salário é de R${:.2f}.'.format(salario))
# Estrutura Condicional if/else
if salario > 1250.00:
novo = salario + (salario * (10 / 100))
else:
novo = salario + (salario * (15 / 100))
print('O salário passará para R${:.2f}.'.format(novo))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_071.py
|
<filename>Python_Exercicios/Mundo3/Listas em Python/python_071.py
'''
Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta.
mostre na tela:
A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
'''
# Fazer a lista da matriz
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# Declarar Variaveis
soma_par = maior = soma_coluna = 0
# Fazer um laço dentro do outro para suprir todas as colunas
# laço for para as linhas
for l in range(0, 3):
#laço for para as colunas
for c in range(0, 3):
matriz[l][c] = int(int(input(f'Digite um valor para [{l}, {c}]: ')))
print('-='* 30)
# Fazer novamente um for com a linha dentro da coluna para mostrar a estrutura na tela
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]:^5}]', end='')
# verificar se um numero é par e fazer a soma quando for
if matriz[l][c] % 2 == 0:
soma_par += matriz[l][c]
print()
print('-='*30)
print(f'A soma dos valores pares é {soma_par}!')
# Fazer um for somente para a coluna e não para a linha
for l in range(0, 3):
soma_coluna += matriz[l][2]
print(f'A soma dos valores da terceira coluna é {soma_coluna}!')
# fazer um for somente para a linha e não para a coluna
for c in range(0, 3):
if c == 0:
maior = matriz[1][c]
elif matriz[1][c] > maior:
maior = matriz[1][c]
print(f'O maior valor da segunda linha é {maior}!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula19.py
|
pessoas = {'nome': 'Josué', 'sexo': 'M', 'idade': 30}
print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.')
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for k in pessoas.keys():# pessoas.items(),pessoas.values()
print(k)
pessoas['peso'] = 67.5
# Criar um dicionário dentro de uma lista
brasil = list()
estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'RJ'}
estado2 = {'uf': 'São Paulo', 'sigla': 'SP'}
brasil.append(estado1)
brasil.append(estado2)
print(brasil[1]['sigla'])
print('-='*30)
# ler dicionarios
estado = dict()
brasil = []
for c in range(0, 3):
estado['uf'] = str(input('Unidade Federativa: '))
estado['sigla'] = str(input('Sigla do Estado: '))
brasil.append(estado.copy())# para fazer uma cópia do dicionário
for e in brasil:
for k, v in e.items():
print(f'O campo {k} tem valor {v}.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_023.py
|
'''
Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
'''
# Leia um número
num = int(input('Informe um número: '))
# Descobrir a Unidade
u = num // 1 % 10
# Descobrir a Dezena
d = num // 10 % 10
# Descobrir a Centena
c = num // 100 % 10
# Descobrir o Milhar
m = num // 1000 % 10
# Imprimir na tela
print('Analisando o número {}.'.format(num))
print('Unidade: {}.'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}.'.format(c))
print('Milhar: {}.'.format(m))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_064.py
|
'''
Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
'''
numeros = list()
# Ler valores enquanto o usuario responder S
while True:
n = int(input('Digite um número: '))
# Quando o numero digitado não for repetido
if n not in numeros:
numeros.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado! Não vou adicionar...')
r = str(input('Quer continuar? Sim ou Não S/N: '))
# Para quebrar a sequencia do laço while
if r in 'nN':
break
print('-='*30)
numeros.sort()
print(f'Você digitou os valores {numeros}!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_065.py
|
'''
Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
'''
lista = list()
# Fazer um laço for para o usuario digitar 5 números
for c in range(0, 5):
n = int(input('Digite um numero: '))
# Se for o primeiro ou maior que o ultimo numero digitado
if c == 0 or n > lista[len(lista)-1]:
lista.append(n)
print('Adicionado ao final da lista...')
else:
# percorrer todas as posições e encontrar a ordem certa para colocar o Número
pos = 0
while pos < len(lista):
if n <= lista[pos]:
lista.insert(pos, n)
print(f'Adicionado na posição {pos} da lista...')
break
pos += 1
print('-='*30)
print('Os números digitados são {lista}')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_032.py
|
<gh_stars>0
'''
Faça um programa que leia um ano qualquer e mostre se ele é bissexto.
'''
# Importar a função date do módulo datetime
from datetime import date
# Ler ano
ano = int(input("Que ano você quer analisar? Coloque 0 para analisar: "))
# Para saber sobre o ano atual
if ano == 0:
ano = date.today().year
# Estrutura Condicional if/else
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('O ano {} é BISSEXTO.'.format(ano))
else:
print('O ano {} não é BISSEXTO.'.format(ano))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_067.py
|
'''
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.
'''
# Aplicar uma lista
numeros = []
pares = []
impares =[]
# Aplicar um laço while que enquanto for verdadeiro pedir para o usuário digitar um número
while True:
numeros.append(int(input('Digite um número: ')))
r = str(input('Deseja continuar? Digite S para continuar ou N para parar: '))
if r in 'Nn':
break
# para saber se o numero é par ou impar
for i, v in enumerate(numeros):
if v % 2 == 0:
pares.append(v)
else:
impares.append(v)
print(f'A lista original tem os valores {numeros}!')
print(f'A lista de pares tem os valores {pares}')
print(f'A lista de impares tem os valores {impares}')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_045.py
|
'''
Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
'''
# Leia um número Inteiro
n = int(input('Digite um número Inteiro: '))
print('A tabuada do número {} é: '.format(n))
# Laço for para fazer a tabuada
for t in range(1, 11):
m = n * t
print('{} x {} = {}'.format(t, n, m))
print('--'*10)
print('FIM')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_049.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (for)/python_049.py<gh_stars>0
'''
Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Exemplos de palíndromos:
APOS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA, O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA.
'''
# Ler frase
frase = str(input('Escreva uma frase: ')).strip().upper()
print('\nVocê digitou a frase: {}'.format(frase))
# Separar a frase por palavras
palavras = frase.split()
# Juntar as palavras sem espaço
junto = ''.join(palavras)
# Iverter as palavras
inverso = ''
# Laço for para inverter a frase
for letra in range(len(junto) - 1, -1, -1):
inverso += junto[letra]
print('O inverso de {} é {}.'.format(junto, inverso))
if inverso == junto:
print('Temos um palíndromo!')
else:
print('Não temos um palíndromo!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_051.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
'''
Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.
'''
# # Média das idades
soma_idade = 0
media_idade = 0
# Homem mais velho
maior_idade_homem = 0
nome_velho = ''
# Quantidade de mulheres que tem menos de 20 anos
total_mulheres20 = 0
# Fazer um laço for para ler o nome de 4 pessoas
for c in range(1, 5):
print('----- {}ª PESSOA -----'.format(c))
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).strip()
soma_idade += idade
# Para saber qual homem mais velho
if c == 1 and sexo in 'Mm':
maior_idade_homem = idade
nome_velho = nome
if sexo in 'Mm' and idade > maior_idade_homem:
maior_idade_homem = idade
nome_velho = nome
if sexo in 'Ff' and idade < 20:
total_mulheres20 += 1
# Calcular a média de idade
media_idade = soma_idade / 4
print('A média de idade do grupo é de {} anos.'.format(media_idade))
print('O homem mais velho tem {} anos e se chama {}.'.format(maior_idade_homem, nome_velho))
print('A quantidade de mulheres com menos de 20 anos é de {}.'.format(total_mulheres20))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula08.b.py
|
import emoji
print(emoji.emojize("<NAME> :earth_americas:", use_aliases=True))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_057.py
|
'''
Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo.
'''
# Importar radint de random
from random import randint
# Escolha Par ou Impar
print('++++ Escolha Par ou Ímpar ++++')
print('**'*20)
print('[1] Ímpar ')
print('[2] Par ')
# Usar randint para o computador escolher um numero aleatório
computador = randint(0, 11)
# Contador de vitórias
vitoria = 0
# Laço while para fazer o jogo e descobrir quem venceu
while True:
jogador = int(input('Digite um 1 ou 2 : '))
# Escolhendo Par
if jogador == 2:
n = int(input('Digite um número : '))
soma = n + computador
if soma % 2 == 0:
print('-=='*20)
print('Você VENCEU!!!')
print('-=='*20)
print(f'O computador escolheu {computador}, e o jogador escolheu {n}.')
print('-=='*20)
elif soma % 2 != 0:
print('-=='*20)
print('Você PERDEU!!!')
print(f'O computador escolheu {computador}, e o jogador escolheu {n}.')
# Quebrar o laço
break
# Escolhendo Impar
if jogador == 1:
n = int(input('Digite um número :'))
soma = n + computador
if soma % 2 != 0:
print('-=='*20)
print('Você VENCEU!!!')
print('-=='*20)
print(f'O computador escolheu {computador}, e o jogador escolheu {n}.')
print('-=='*20)
elif soma % 2 == 0:
print('-=='*20)
print('Você PERDEU!!!')
print(f'O computador escolheu {computador}, e o jogador escolheu {n}.')
# Quebrar o laço
break
vitoria += 1
print(f'O número de vitórias consecutivas do jogador foi {vitoria}.')
print('-=='*20)
print('FIM DE JOGO')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_047.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
'''
Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão.
'''
# Ler o primeiro ter a razão
pt = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
contador = 0
for i in range(pt, 100, r):
contador = contador + 1
if contador <= 10:
print('-> ', end='')
print(i, end=' ')
print('Acabou!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_031.py
|
'''
Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km, e R$0,45 para viagens mais longas.
'''
# Ler Distância
distancia = int(input('Informe a distância que será percorrida: '))
print('A distância é de {}Km.'.format(distancia))
print('--'* 30)
# Estrutura Condicional if/else.
if distancia <= 200:
print('O custo da passagem é de R${:.2f}.'.format(distancia * 0.50))
else:
print('O custo da passagem é de R${:.2f}.'.format(distancia * 0.45))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Primeiros_passos_com_python/python_001.py
|
print('Olá, Mundo!')
subst = "Python"
verbo = "é"
adjetivo = "fantástico"
print(subst, verbo, adjetivo, sep="_", end="!\n")
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_054.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (while)/python_054.py
'''
Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
'''
# Ler dois valores
n1 = int(input('Digite um primeiro valor: '))
n2 = int(input('Digite um segundo valor: '))
# Menu de Operaçôes
print('[ 1 ] somar')
print('[ 2 ] multiplicar')
print('[ 3 ] maior')
print('[ 4 ] novos números')
print('[ 5 ] sair do programa')
escolha = int(input('Escolha um número: '))
# Laço while para escolher uma operação
while escolha != 5:
if escolha == 1:
print('A soma de {} e {} é igual a {}.'.format(n1, n2, (n1+ n2)))
elif escolha == 2:
print('A multiplicação de {} e {} é igual a {}.'.format(n1, n2, (n1*n2)))
elif escolha == 3:
if n1 > n2:
print('O número maior é {}.'.format(n1))
else:
print('O número maior é {}.'.format(n2))
elif escolha == 4:
n1 = int(input('Digite um primeiro valor: '))
n2 = int(input('Digite um segundo valor: '))
escolha = int(input('Escolha um número: '))
print('FIM DO PROGRAMA!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_070.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python<gh_stars>0
'''
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
'''
# Declarar duas listas internas
num = [[], []]
# Variaveis
valores = 0
# Fazer um laço for com um contador
for c in range(1, 8):
valor = int(input(f'Digite o {c}o. valor: '))
# Para colocar o valor na posição de par
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
print('-=' * 30)
# Para colocar em ordem crescente
num[0].sort()
num[1].sort()
print(f'Todos os valores: {num}!')
# Imprimir só os valores pares
print(f'Os valores pares são {num[0]}')
# Imprimir só os valores impares
print(f'Os valores pares são {num[1]}')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Dicionários em Python/python_075.py
|
'''
Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
'''
# Fazer um diiconario para jogador
jogador = {}
# Fazer uma lista para partidas
partidas = list()
# Ler nome do jogador
jogador['nome'] = str(input('Nome do Jogador: '))
tot_partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
# Fazer um for para acrescentar partidas no histórico do jogador
for c in range(0, tot_partidas):
partidas.append(int(input(f' Qunatos gols na partida {c +1} fez? ')))
# Passar lista para o dicionario e fazer cópias da lista
jogador['gols'] = partidas[:]
jogador['total_gols'] = sum(partidas)
print('-=' * 30)
print(jogador)
print('-=' * 30)
for k, v in jogador.items():
print(f'O campo {k} tem o valor {v}.')
print('-=' * 30)
print(f'O jogador {jogador["nome"]} jogou {len(jogador["gols"])} partidas.')
for i, v in enumerate(jogador['gols']):
print(f' => Na partida {i + 1}, fez {v} gols.')
print(f'Foi um total de {jogador["total_gols"]} gols.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_024.py
|
<filename>Python_Exercicios/Mundo1/Utilizando Módulos/python_024.py<gh_stars>0
'''
Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome "SANTO".
'''
# Leia o nome de uma cidade
cidade = str(input('Digite o nome de uma cidade: ')).strip()
# Imprimir na tela
print('santo' in cidade[:5].lower())
# Imprimir outra maneira
print(cidade[:5].upper() == 'SANTO')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_042.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
'''
Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
'''
# Importar sleep que conta um segundo
from time import sleep
# Laço for para contagem regressiva
for i in range(10, 0, -1):
print(i)
sleep(1)
print()
print('**'*10)
print()
print('FELIZ ANO NOVO!!!!')
print()
print('**'*10)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_048.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (for)/python_048.py
'''
Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
'''
# Ler um número inteiro
n = int(input('Digite um número: '))
contador = 0
#Laço for para fazer a divisão e saber por quantos números é divisivel
for c in range(1, n+1):
if n % c == 0:
print('\033[1;34m', end=' ')
contador += 1
else:
print('\033[31m', end=' ')
print('{}'.format(c), end=' ')
print('\n\033[mO número {} foi divisível {} vezes.'.format(n, contador))
# Para saber se o número é primo
if contador == 2:
print('E por isso ele é primo!')
else:
print('E por isso ele não é primo!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_053.py
|
<gh_stars>0
'''
Melhore o jogo do DESAFIO 28 onde o computador vai “pensar” em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
'''
# Importar função randint do módulo random
from random import randint
# Contador de tentativas
contador = 0
# Número que o computador pensa
computador = randint(0 , 5)
print('-=-'*20)
print('Olá! Pensei em um número de 0 a 10. Consegue adivinhar?')
print('-=-'*20)
# A tentativa do jogador de adivinhar
jogador = int(input('Em que número eu pensei? '))
print('###'*20)
# Laço while até o jogador acertar
while computador != jogador:
jogador = int(input('Tente no novamente: '))
contador += 1
# Estrutura Condicional if/else
if jogador == computador:
print('____PARABÉNS! Você VENCEU!!!____')
elif jogador > 10:
print('Você é muito burro! Eu disse de 0 a 5. Acabou o jogo!')
# Imprimir o número que o computador pensou
print('Você precisou de {} tentativas.'.format(contador))
print('###'*20)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_052.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (while)/python_052.py
'''
Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores ‘M’ ou ‘F’. Caso esteja errado, peça a digitação novamente até ter um valor correto.
'''
n = 'Augusto'
if n in 'aeiou' :
print('sim')
# Ler o nome e o sexo de uma pessoa
nome = str(input('Nome: '))
sexo = str(input('Sexo: ')).strip().upper()[0]
idade = int(input('Idades: '))
# Laço while para digitar novamente se a pessoa escrever errado
while sexo not in 'MmFf':
sexo = str(input('Digite novamente o sexo: ')).strip().upper()[0]
print('O seu nome é {}, e o seu sexo é {}.'.format(nome, sexo))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_005.py
|
'''
Faça um programa que leia um número Inteiro e mostre
na tela o seu sucessor e seu antecessor.
'''
# Ler um número Inteiro
n = int(input('Digite um número: '))
# Imprimir na tela
print(n)
print('O sucessor de {} é {}.'.format(n, (n + 1)))
print('O antecessor de {} é {}.'.format(n, (n - 1)))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_055.py
|
<gh_stars>0
'''
Faça um programa que leia um número qualquer e mostre o seu fatorial.
Exemplo:
5! = 5 x 4 x 3 x 2 x 1 = 120
'''
# Ler um número
n = int(input('Digite um número: '))
c = n
fatorial = 1
print('Calculando {}! = '.format(n), end='')
# Laço while para fazer o fatorial
while c > 0:
print('{}'.format(c), end='')
print(' X ' if c > 1 else ' = ', end='')
fatorial *= c
c -= 1
print('{}'.format(fatorial))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_041b.py
|
'''
Crie um programa que faça o computador jogar Jokenpô com você.
'''
from random import randint
# Esperando 1 segundo dizendo Jokenpo
from time import sleep
# Fazer uma Lista
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0, 2)
print('[0] PEDRA: ')
print('[1] PAPEL: ')
print('[2] TESOURA: ')
jogador = int(input('Escolha: '))
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
sleep(1)
print('-='*40)
print('A escolha do usuário foi {} e a escolha do computador foi {}.'.format(itens[jogador], itens[computador]))
print('-='*40)
if computador == 0:
if jogador == 0:
print('EMPATE')
elif jogador == 1:
print('Jogador VENCE!')
elif jogador == 2:
print('Computador VENCE!')
else:
print('Jogada Inválida!')
if computador == 1:
if jogador == 0:
print('Computador VENCE!')
elif jogador == 1:
print('EMPATE')
elif jogador == 2:
print('Jogador VENCE!')
else:
print('Jogada Inválida!')
if computador == 2:
if jogador == 0:
print('Jogador VENCE!')
elif jogador == 1:
print('Computador VENCE!')
elif jogador == 2:
print('EMPATE')
else:
print('Jogada Inválida!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula09a.py
|
<gh_stars>0
frase = 'Curso em Vídeo Python'
frase2 = ' Aprenda Python '
print(frase[3])
print(frase[3:13])
print(frase[:13])
print(frase[13:])
print(frase[9:21:2])
print(frase[9::3])
print(frase[::2])
print(len(frase))
print(frase.count('o'))
print(frase.find('deo'))
print(frase.find('Android'))
print('Curso' in frase)
print(frase.replace('Python', 'Android'))
print(frase.upper())
print(frase.lower())
print(frase.capitalize())
print(frase.title())
print(frase.split())
print('-'.join(frase))
print(frase.upper().count('O'))
print(frase2.strip())
print(frase2.rstrip())
print(frase2.lstrip())
print('''Python is a programming language that lets you work quickly and integrate systems more effectively.''')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_046.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (for)/python_046.py
'''
Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o.
'''
# soma
s = 0
# Ler 6 números inteiros usando laço for
for i in range(0, 6):
n = int(input('Digite um número inteiro: '))
if n % 2 == 0:
s = s + n
print('A soma dos pares é {}.'.format(s))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_010.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python<filename>Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_010.py<gh_stars>0
'''
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostra quantos Dólares ela pode comprar.
'''
# Leia o valor que tem na carteira
r = float(input('Digite quanto de dinheiro você possui na carteira: '))
# Transformar para dólar
d = float(r / 3.27)
# Imprimir na Tela
print('Tem {:.2f}R$ na carteira'.format(r))
print('Isso equivale a {:.2f}$ dólares.'.format(d))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula21.py
|
def fatorial(num=1):
f = 1
for c in range(num, 0, -1):
f *= c
return f
f1 = fatorial(5)
f2 = fatorial(4)
f3 = fatorial()
print(f'Os resultados são {f1}, {f2}, {f3}.')
def par(n=0):
if n % 2 == 0:
return True
else:
return False
num = int(input('Digite um número: '))
if par(num):
print(f'{num} é par!')
else:
print(f'{num} não é par!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_029.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
'''
Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.
'''
# Ler a velocidade do carro.
vc = int(input('Informe a velocidade do carro: '))
print('--*-'* 20)
print('A velocidade registrada é de {}Km/h.'.format(vc))
print('--*-'* 20)
# Estrutura Condicional if/else
if vc > 80:
print('Você foi MULTADO! Pois excedeu o limite de 80Km/h. E agora deve R${:.2f} reais.'.format((vc - 80) * 7))
else:
print('PARABÉNS!!!!')
print('--$-'* 20)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (for)/python_050.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python
'''
Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
'''
# Importar o ano atualizado do datatime.
from datetime import date
ano_atual = date.today().year
# Contadores
menor = 0
maior = 0
# Laço for para ler o nome de sete pessoas
for p in range(1 , 8):
ano_nascimento = int(input('Qual o ano de nascimento: '))
if ano_atual - ano_nascimento < 18:
menor = menor + 1
elif ano_atual - ano_nascimento > 18:
maior = maior + 1
print('O número de pessoas que atingiram a maioridade é {}.'.format(maior))
print('O número de pessoas que não atingiram a maioridade é {}.'.format(menor))
print('FIM!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_016.py
|
'''
Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira
'''
# Importar a biblioteca math e floor
from math import floor
# Ler um número Real
n= float(input('Digite um número: '))
# Imprimir o número Inteiro
print('O número {} tem a parte inteira {}.' .format(n, floor(n)))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_022.py
|
'''
Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiusculas e minusculas.
- Quantas letras ao todo (sem considerar espaços).
- Quantas letras tem o primeiro nome.
'''
# Ler o nome completo
nome = str(input('Digite o seu nome: ')).strip()
# Imprimir o nome completo
print(nome)
# Imprimir com letras maiusculas
print('O nome com todas as letras maiusculas')
print(nome.upper())
# Imprimir com letras minusculas
print('O nome com todas as letras minusculas.')
print(nome.lower())
# Imprimir quantidade de letras ao todo (sem considerar espaços).
print('Quantas letras ao todo (sem considerar espaços).')
print(len(nome)-nome.count(' '))
# Imprimir quantas letras tem no primeiro nome.
print('Quantas letras tem o primeiro nome.[Parte 1]')
print(nome.find(' '))
# Outra maneira de fazer quantas letras tem no primeiro nome.
print('Quantas letras tem o primeiro nome.[Parte 2]')
separa = nome.split()
print(len(separa[0]))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_019.py
|
<gh_stars>0
'''
Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido.
'''
# Importar o randomizador de elementos
from random import choice
# Leia os 4 nomes
n1 = str(input('Digite um nome: '))
n2 = str(input('Digite um nome: '))
n3 = str(input('Digite um nome: '))
n4 = str(input('Digite um nome: '))
# Fazer uma lista
lista = [n1, n2, n3 ,n4]
# Sortear um nome da lista
escolhido = choice(lista)
# Imprimir
print('O aluno escolhido foi {}.'.format(escolhido))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_026.py
|
'''
Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
'''
# Ler uma frase
frase = str(input('Escreva uma frase: ')).lower().strip()
# Imprimir
print('Quantos As tem na frase? {}'.format(frase.count('a')))
print('Em que posição a letra A aparece a primeira vez? {}'.format(frase.find('a') + 1))
print('Em que posição a letra A aparece por último? {}'.format(frase.rfind('a') + 1))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Utilizando Módulos/python_025.py
|
'''
Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
'''
# Ler o nome completo de uma pessoa
nome = str(input('Digite o nome: '))
# Imprimir nome
print('silva' in nome.lower())
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Funções em Python/python_077.py
|
<gh_stars>0
'''
Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.
'''
# Criar uma função para calcular a area, que recebera dois parametros l = largura e c = comprimento.
def area(l, c):
a = l * c
print(f'A área de um terreno {l} x {c} é de {a}m².')
# Programa Principal
print(' Controle de Terrenos')
print('_'* 20)
l = float(input('LARGURA (m): '))
c = float(input('COMPRIMENTO (m): '))
area(l, c)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_037.py
|
<reponame>jbauermanncode/Curso_Em_Video_Python<filename>Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_037.py
'''
Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.
'''
# Ler um número inteiro e definr a base
n = int(input('Digite um número: '))
base = int(input('Em qual base será feita a conversão? '))
print('[1] Para Binário')
print('[2] Para Octal')
print('[3] Para Hexadecimal')
# Conversão para binário, hexadecimal, octal, com Estrutura Condicional if, elif, else.
if base == 1:
print('O número {}, fica {} em binário.'.format(n, bin(n)[2:]))
elif base == 2:
print('O número {}, fica {} em octal.'.format(n, oct(n)[2:]))
elif base == 3:
print('O número {}, fica {} em hexadecimal.'.format(n, hex(n)[2:]))
else:
print('O número de base não está listado')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Listas em Python/python_063.py
|
'''
Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
'''
# Indicar uma lista
valores = list()
# Usar o laço for para ler numeros
for cont in range(0, 5):
valores.append(int(input('Digite um valor: ')))
# Usar o laço for para ver o numero e a posição
for p, v in enumerate(valores):
# Procurar o numero maior usando max e imprimir na tela
if v == max(valores):
print(f'O maior valor é {v} e a posição é {(p) + 1}!')
# Procurar o numero menor usando min e imprimir na tela
if v == min(valores):
print(f'O menor valor é {v} e a posição é {(p) + 1}!')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_030.py
|
'''
Crie um programa que leia um número inteiro e mostre na tela se ele é par ou ímpar.
'''
# Ler um número
n = int(input('Digite um número: '))
# Estrutura Condicional if/else
if n % 2 == 0:
print('O número {} é par!'.format(n))
else:
print('O número {} é ímpar!'.format(n))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula16.py
|
<gh_stars>0
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
print(lanche[0:4])
print()
print('-++'*20)
print()
# Usando laço for
for cont in range(0, len(lanche)):
print(lanche[cont])
print()
print('-++'*20)
print()
for comida in lanche:
print(f'Eu vou comer {comida}.')
print()
print('-++'*20)
print()
# Para saber a posição
for cont in range(0, len(lanche)):
print(f'Eu vou comer {lanche[cont]} na posição {cont}.')
print()
print('-++'*20)
print()
# Para saber a posição usando enumerate
for pos, comida in enumerate(lanche):
print(f'Eu vou comer {comida} na posição {pos}.')
print()
print('-++'*20)
print()
# Mostrar o lanche em ordem
print(sorted(list(lanche)))
print()
print('-++'*20)
print()
print('Comi pra caramba!')
print()
print('-++'*20)
print()
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print(c)
print(c.index(4))
print()
print('-++'*20)
print()
pessoa = ('Gustavo', 39, 'M', 99.88)
print(pessoa)
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Repetições em Python (while)/python_058.py
|
<filename>Python_Exercicios/Mundo2/Repetições em Python (while)/python_058.py<gh_stars>0
'''
Crie um programa que tenha uma Tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
'''
# Tupla com números por extenso
extenso = ('Zero','Um','Dois','Três','Quatro','Cinco','Seis','Sete','Oito','Nove','Dez','Onze','Doze','Treze','Quatorze','Quinze','Dezesseis','Dezessete','Dezoito','Dezenove','Vinte')
# Ler um número e imprimir ele por extenso
while True:
n = int(input('Digite um número de 0 à 20: '))
if 0 <= n <= 20:
break
print('Tente novamente.', end= '\n')
print(f'Você digitou {extenso[n]}.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula11.py
|
print('\033[7;33;44mOlá, Mundo!\033[m')
a = 3
b = 5
print('Os valores são \033[32m{}\033[m e \033[31m{}\033[m!!!'.format(a, b))
# Outra maneira de fazer
nome = 'Josué'
print('Olá! Muito prazer em te conhecer, {}{}{}!!!'.format('\033[4;34m', nome, '\033[m'))
# Outra maneira
nome = 'Josué'
cores = {
'limpa' : '\033[m',
'azul': '\033[34m',
'amarelo': '\033[33m',
'preto e branco': '\033[7;30m'
}
print('Olá! Muito prazer em te conhecer, {}{}{}!!!'.format(cores['preto e branco'], nome, cores['limpa']))
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_040.py
|
'''
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. Informe:
– EQUILÁTERO: todos os lados iguais
– ISÓSCELES: dois lados iguais, um diferente
– ESCALENO: todos os lados diferentes
'''
print('-='*20)
print('Analisador de Triângulos')
print('-='*20)
# Ler 3 retas
r1 = float(input('Informe o valor: '))
r2 = float(input('Informe o valor: '))
r3 = float(input('Informe o valor: '))
# Usando Operadores Relacionais
equilatero = r1 == r2 == r3
isosceles = (r1 == r2 != r3) or (r1 == r3 != r2) or (r2 == r3 != r1)
escaleno = r1 != r2 != r3 != r1
# Estrutura Condicional if, elif, else
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos acima podem formar um triângulo!', end=' ')
if equilatero:
print('EQUILÁTERO!')
elif isosceles:
print('ISÓSCELES!')
elif escaleno:
print('ESCALENO!')
else:
print('Os segmentos acima não podem formar um triângulo')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_035.py
|
<gh_stars>0
'''
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
'''
print('-='*20)
print('Analisador de Triângulos')
print('-='*20)
# Ler 3 retas
r1 = float(input('Informe o valor: '))
r2 = float(input('Informe o valor: '))
r3 = float(input('Informe o valor: '))
# Estrutura Condicional if/else
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos acima podem formar um triângulo!')
else:
print('Os segmentos acima não podem formar um triângulo')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Tuplas em Python/python_059.py
|
'''
Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.
'''
from random import randint
# Randomizar 5 números
numeros = (randint(1, 10),randint(1, 10),randint(1, 10),randint(1, 10),randint(1, 10))
print('Os valores sorteados foram: ', end='')
for n in numeros:
print(f'{n} ', end='')
# Usando método max das tuplas para saber o maior e menor
print(f'\nO maior valor sorteado foi {max(numeros)}.')
print(f'O menor valor sorteado foi {min(numeros)}.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Test/aula18.py
|
<gh_stars>0
print('Lista 1')
teste = list()
teste.append('Gustavo')
teste.append(40)
galera = list()
galera.append(teste[:])
teste[0] = 'Maria'
teste[1] = 22
galera.append(teste[:])
print(galera)
print('-='*30)
print()
print('Lista 2')
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
for p in galera:
print(f'{p[0]} tem {p[1]} anos de idade.')
print('-='*30)
print()
print('Lista 3')
galera = list()
dado = list()
total_maior = total_menor = 0
for c in range(0, 3):
dado.append(str(input('Nome: ')))
dado.append(float(input('Idade: ')))
galera.append(dado[:])
dado.clear()
for p in galera:
if p[1] >= 21:
print(f'{p[0]} é maior de idade.')
total_maior += 1
else:
print(f'{p[0]} é menor de idade.')
total_menor += 1
print(f'Temos {total_maior} maiores e {total_menor} menores de idade.')
|
jbauermanncode/Curso_Em_Video_Python
|
Python_Exercicios/Mundo3/Dicionários em Python/python_072.py
|
'''
Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela.
'''
# Fazer um dicionario para aluno
aluno = dict()
# Pedir nome e média do aluno
aluno['nome'] = str(input('Nome: '))
aluno['média'] = float(input(f'Média de {aluno["nome"]}: '))
# Definir a situação do aluno em relação a média
if aluno['média'] >= 7:
aluno['situação'] = 'Aprovado'
elif 5 <= aluno['média'] < 7:
aluno['situação'] = 'Recuperação'
else:
aluno['situação'] = 'Reprovado'
print('-=' * 30)
# Fazer um for para imprimir na tela
for k, v in aluno.items():
print(f'{k} é igual a {v}.')
|
skorani/tokenizer
|
tokenizer/_tokenizer.py
|
import logging
from flashtext import KeywordProcessor
log = logging.getLogger(f"pizza_nlp.{__name__}")
class Tokenizer(object):
def __init__(self):
log.info("Tokenizer initialization")
from .lookup_dic import _PhraseDictionary as __PD
log.debug("Tokenizer: calls lookup_dic.read_phrases")
self.lookup_dic = __PD()
log.debug("Instanciate flashtext.KeyworkProcessor")
self.__keyword_processor = KeywordProcessor()
log.debug("Insert data into flashtext.KeyworkProcessor instance.")
self.__keyword_processor.add_keywords_from_dict(
self.lookup_dic.lookup_dic_CODE)
log.info("Tokenizer initialization successful")
def tokenize(self, text):
log.debug(f"Tokenizer called on {text}")
log.debug("Phase I: Replacing phrases.")
text = self.__keyword_processor.replace_keywords(text)
log.debug("Phase II: Split by space.")
tokens_list = text.split()
log.debug("Phase III: Replace back token id to its original form.")
tokens_list = [
self.lookup_dic.reverse_replace(token)
if token in self.lookup_dic.lookup_dic_CODE else token
for token in tokens_list
]
return tokens_list
def __call__(self, text):
return self.tokenize(text)
|
skorani/tokenizer
|
main.py
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
from collections import Counter
from tokenizer import Tokenizer
logging.basicConfig()
def main():
clean_text = [input()]
tok = Tokenizer()
for text in clean_text:
tokens = tok(text)
print(tokens)
counts = Counter(tokens)
for token, count in counts.items():
print(f"{token}: {count}")
if __name__ == "__main__":
main()
|
skorani/tokenizer
|
tokenizer/__init__.py
|
import logging as __logging
from ._tokenizer import Tokenizer
__logging.getLogger(f"pizza_nlp.{__name__}").addHandler(__logging.NullHandler())
|
skorani/tokenizer
|
tokenizer/lookup_dic.py
|
import csv
import logging
log = logging.getLogger(f"pizza_nlp.{__name__}")
class _PhraseDictionary(object):
def __init__(self, phrase_file="data/phrases.csv"):
self._phrase_file = phrase_file
log.debug("Populating phrase dictionary: started")
self.lookup_reverse_dic_CODE = dict()
self.lookup_dic_CODE = dict()
log.debug("Reading phrase datafile: started")
log.info("Reading phrase datafile: {}".format(phrase_file))
with open(phrase_file) as f:
reader = csv.reader(f)
for row in reader:
try:
phrase, replace_with = row
log.debug(f" phrase: {phrase}, rw: {replace_with}")
except ValueError:
log.error(
"Bad input: {} - "
"csv parser could not unpack properly.".format(
repr(row)))
self.lookup_dic_CODE.update({replace_with: [phrase]})
self.lookup_reverse_dic_CODE.update({phrase: [replace_with]})
log.debug(
f"Phrase: {phrase} with id {replace_with}"
"added to phrase dictionary.")
log.debug("Populating phrase dictionary: finished")
def reverse_replace(self, _token_):
log.debug(f'Reverse lookup call for "{_token_}".')
for item in self.lookup_dic_CODE.items():
_token_ = str.replace(_token_, item[0], item[1][0])
log.debug(f'Found "{_token_}".')
return _token_
|
312shan/gpt-2
|
src/flask_conditional_samples.py
|
<filename>src/flask_conditional_samples.py
#!/usr/bin/env python3
import json
import os
import numpy as np
import tensorflow as tf
import model, sample, encoder
from flask import Flask, request
app = Flask(__name__)
model_name = '124M'
seed = None
nsamples = 1
batch_size = 1
length = None
temperature = 1
top_k = 0
top_p = 1
models_dir = 'models'
models_dir = os.path.expanduser(os.path.expandvars(models_dir))
if batch_size is None:
batch_size = 1
assert nsamples % batch_size == 0
enc = encoder.get_encoder(model_name, models_dir)
hparams = model.default_hparams()
with open(os.path.join(models_dir, model_name, 'hparams.json')) as f:
hparams.override_from_dict(json.load(f))
if length is None:
length = hparams.n_ctx // 2
elif length > hparams.n_ctx:
raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx)
class Serving:
def __init__(self):
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
self.context = tf.placeholder(tf.int32, [batch_size, None])
np.random.seed(seed)
tf.set_random_seed(seed)
self.output = sample.sample_sequence(
hparams=hparams, length=length,
context=self.context,
batch_size=batch_size,
temperature=temperature, top_k=top_k, top_p=top_p
)
saver = tf.train.Saver()
ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, model_name))
saver.restore(self.sess, ckpt)
def model_run(self, raw_text):
context_tokens = enc.encode(raw_text)
generated = 0
res = []
for _ in range(nsamples // batch_size):
out = self.sess.run(self.output, feed_dict={
self.context: [context_tokens for _ in range(batch_size)]
})[:, len(context_tokens):]
for i in range(batch_size):
generated += 1
text = enc.decode(out[i])
print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
print(text)
res.append("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
res.append(text)
print("=" * 80)
res.append("=" * 80)
return "<br/>".join(res)
@app.route('/api', methods=['GET', 'POST'])
def main():
if request.method == 'POST':
raw_text = request.get_json()['text']
else:
raw_text = request.args.get("text")
print("Context: %s" % raw_text)
texts = serve.model_run(raw_text)
return texts
if __name__ == '__main__':
serve = Serving()
app.run(host='0.0.0.0', port='5000', debug=True)
|
alnah005/raccoon_identification
|
Generate_Individual_IDs_dataset/split_training_test.py
|
# -*- coding: utf-8 -*-
"""
file: split_training_test.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-06T19:03:55.206Z-05:00
@last-modified: 2021-04-06T19:13:06.727Z-05:00
"""
# standard library
# 3rd party packages
# local source
import os
import shutil
import random
#Prompting user to enter number of files to select randomly along with directory
source=input("Enter the Source Directory : ")
dest=input("Enter the Destination Directory : ")
no_of_files=int(input("Enter The Number of Files To Select : "))
print("%"*25+"{ Details Of Transfer }"+"%"*25)
print("\n\nList of Files Moved to %s :-"%(dest))
#Using for loop to randomly choose multiple files
for i in range(no_of_files):
#Variable random_file stores the name of the random file chosen
random_file=random.choice(list(sorted([i for i in os.listdir("croppedImages") if (('.png' in i) or ('.jpg' in i) or ('.jpeg' in i))])))
print("%d} %s"%(i+1,random_file))
source_file="%s/%s"%(source,random_file)
dest_file=dest
#"shutil.move" function moves file from one directory to another
shutil.move(source_file,dest_file)
print("\n\n"+"$"*33+"[ Files Moved Successfully ]"+"$"*33)
|
alnah005/raccoon_identification
|
Triplet_Loss_Framework/config_local.py
|
# -*- coding: utf-8 -*-
"""
file: config.py
@author: Suhail.Alnahari
@description: This file contains all possible configurations for the [metric_loss.py] file
@created: 2021-04-07T09:33:39.899Z-05:00
@last-modified: 2021-04-19T10:00:01.801Z-05:00
"""
# standard library
import os
# 3rd party packages
from torchvision import transforms, models, datasets
import torch.nn as nn
import torch
from pytorch_metric_learning.utils import common_functions
from pytorch_metric_learning import losses, miners, distances, reducers
# local source
import local_dataset as DS
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MLP(nn.Module):
# layer_sizes[0] is the dimension of the input
# layer_sizes[-1] is the dimension of the output
def __init__(self, layer_sizes, final_relu=False):
super().__init__()
layer_list = []
layer_sizes = [int(x) for x in layer_sizes]
num_layers = len(layer_sizes) - 1
final_relu_layer = num_layers if final_relu else num_layers - 1
for i in range(len(layer_sizes) - 1):
input_size = layer_sizes[i]
curr_size = layer_sizes[i + 1]
if i < final_relu_layer:
layer_list.append(nn.ReLU(inplace=False))
layer_list.append(nn.Linear(input_size, curr_size))
self.net = nn.Sequential(*layer_list)
self.last_linear = self.net[-1]
def forward(self, x):
return self.net(x)
class Embedder(nn.Module):
def __init__(self, trunk,embedder_head, trunk_optimizer,embedder_head_optimizer,checkpointLocation="./experiment"):
super().__init__()
self.trunk = trunk
self.embedder_head = embedder_head
self.trunk_optimizer = trunk_optimizer
self.embedder_head_optimizer = embedder_head_optimizer
self.checkpointLocation = checkpointLocation
if not(os.path.isdir(checkpointLocation)):
os.mkdir(checkpointLocation)
def __call__(self,x):
return self.forward(x)
def train(self):
self.embedder_head.train()
self.trunk.train()
def eval(self):
self.embedder_head.eval()
self.trunk.eval()
def optimize(self):
self.embedder_head_optimizer.step()
self.trunk_optimizer.step()
def zero_grad(self):
self.trunk_optimizer.zero_grad()
self.embedder_head_optimizer.zero_grad()
def forward(self, x):
return self.embedder_head(self.trunk(x))
def save(self, epoch):
torch.save({
'epoch': epoch,
'trunk_state_dict': self.trunk.state_dict(),
'trunk_optimizer_state_dict': self.trunk_optimizer.state_dict(),
'embedder_head_state_dict': self.embedder_head.state_dict(),
'embedder_head_optimizer_state_dict': self.embedder_head_optimizer.state_dict(),
}, os.path.join(self.checkpointLocation,f"model_{epoch}.pt"))
def load(self):
path = self._findMostRecent()
if (len(path) == 0):
return None
checkpoint = torch.load(os.path.join(self.checkpointLocation,path))
self.trunk.load_state_dict(checkpoint['trunk_state_dict'])
self.trunk_optimizer.load_state_dict(checkpoint['trunk_optimizer_state_dict'])
self.embedder_head.load_state_dict(checkpoint['embedder_head_state_dict'])
self.embedder_head_optimizer.load_state_dict(checkpoint['embedder_head_optimizer_state_dict'])
epoch = checkpoint['epoch']
self.train()
return epoch
def _findMostRecent(self) -> str:
model_ckps = list(sorted([i for i in os.listdir(self.checkpointLocation) if ('.pt' in i)]))
if (len(model_ckps) == 0):
return ""
latest_model = ""
maximum_epoch = 0
for i in model_ckps:
_, epoch = i.split('_')
epoch = int(epoch[:-3])
if (epoch > maximum_epoch):
maximum_epoch = epoch
latest_model = i
print(f"Loading model {latest_model} at epoch {maximum_epoch}")
return latest_model
# Set the image transforms
train_transform = transforms.Compose([
# transforms.Resize((250,200)),
# transforms.RandomResizedCrop(scale=(0.16, 1), ratio=(0.75, 1.33), size=64),
transforms.Lambda(lambda image: image.convert('RGB')),
transforms.RandomHorizontalFlip(0.5),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
val_transform = transforms.Compose([
# transforms.Resize((250,200)),
transforms.Lambda(lambda image: image.convert('RGB')),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# Set trunk model and replace the softmax layer with an identity function
trunk = models.resnet50(pretrained=True)
trunk_output_size = trunk.fc.in_features
trunk.fc = common_functions.Identity()
trunk = torch.nn.DataParallel(trunk.to(device))
# Set embedder model. This takes in the output of the trunk and outputs 64 dimensional embeddings
embedder_head = torch.nn.DataParallel(MLP([trunk_output_size, 2]).to(device))
# Set optimizers
embedder_head_optimizer = torch.optim.Adam(embedder_head.parameters(), lr=0.001, weight_decay=0.0001)
trunk_optimizer = torch.optim.Adam(trunk.parameters(), lr=0.0001, weight_decay=0.0001)
def read_checkpoint_config(ckpt_loc="/home/fortson/alnah005/raccoon_identification/Triplet_Loss_Framework/experiment",config_name='config.txt'):
f = open(os.path.join(ckpt_loc,config_name))
lines = f.readlines()
f.close()
if (len(lines) > 0):
f = open(os.path.join(ckpt_loc,config_name),'a')
f.write(f"experiment_{len(lines)}\n")
f.close()
return os.path.join(ckpt_loc,lines[-1].replace('\n','')),os.path.join(ckpt_loc,f"experiment_{len(lines)}")
else:
f = open(os.path.join(ckpt_loc,config_name),'a')
f.write('experiment_0\n')
f.close()
return None, os.path.join(ckpt_loc,'experiment_0')
prev_checkpoint,checkpoint_loc = read_checkpoint_config()
embedder = Embedder(trunk,embedder_head,trunk_optimizer,embedder_head_optimizer,checkpointLocation=checkpoint_loc)
# Set Metric learning parameters
distance = distances.LpDistance(normalize_embeddings=True,p=2,power=1)
reducer_dict = {"triplet": reducers.ThresholdReducer(0.1), "triplet": reducers.MeanReducer()}
reducer = reducers.MultipleReducers(reducer_dict)
metric_loss = losses.TripletMarginLoss(margin = 0.2, distance = distance, reducer = reducer,swap=True)
miner = miners.TripletMarginMiner(margin = 0.2, distance = distance, type_of_triplets = "semihard")
# Set other training parameters
batch_size = 64
num_epochs = 25
class DatasetWrapper(torch.utils.data.Dataset):
def __init__(self,dataset,train=True,split_targets=False):
self.dataset = dataset
self.targets = None
self.split_targets = split_targets
if not(prev_checkpoint is None):
if (train):
print("loading from "+os.path.join(prev_checkpoint,'train_clustering_labels.pt'))
self.targets = torch.load(os.path.join(prev_checkpoint,'train_clustering_labels.pt'))
else:
print("loading from "+os.path.join(prev_checkpoint,'test_clustering_labels.pt'))
self.targets = torch.load(os.path.join(prev_checkpoint,'test_clustering_labels.pt'))
def __getitem__(self, idx):
img, target = self.dataset[idx]
if (self.split_targets):
target += (idx%10)*10
if not(self.targets is None):
target = self.targets[idx].item()
return img, target
def __len__(self):
return len(self.dataset)
def refresh(self):
try:
self.dataset.refresh()
except:
print("no refresh method found")
def __iter__(self,idx=0):
try:
while(idx < len(self)):
idx+= 1
yield self[idx-1]
except:
print("no iter method found")
# train_dataset = DatasetWrapper(DS.RaccoonDataset(img_folder="/home/fortson/alnah005/raccoon_identification/Generate_Individual_IDs_dataset/croppedImages/train",transforms = train_transform))
# val_dataset = DatasetWrapper(DS.RaccoonDataset(img_folder="/home/fortson/alnah005/raccoon_identification/Generate_Individual_IDs_dataset/croppedImages/test", transforms = val_transform),train=False)
train_dataset = DatasetWrapper(datasets.FashionMNIST(root = './', train=True, download=True, transform=train_transform),split_targets=True)
val_dataset = DatasetWrapper(datasets.FashionMNIST(root = './', train=False, download=True, transform=val_transform),train=False,split_targets=True)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True,num_workers=1)
test_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size,num_workers=1)
feedback_every = 2
def feedback_callback(epoch, i, loss, miner) -> str:
return f"Epoch {epoch} Iteration {i}: Loss = {loss}, Number of mined triplets = {miner.num_triplets}"
save_model_every_epochs = 20
|
alnah005/raccoon_identification
|
Triplet_Loss_Framework/local_dataset.py
|
# -*- coding: utf-8 -*-
"""
file: dataset.py
@author: Suhail.Alnahari
@description: Pytorch Custom dataset that expects raccoon images and a label csv file
@created: 2021-04-06T18:27:51.082Z-05:00
@last-modified: 2021-04-13T10:55:09.697Z-05:00
"""
# standard library
import os
# 3rd party packages
import pandas as pd
from PIL import Image
import torch.utils.data as data
# local source
class RaccoonDataset(data.Dataset):
labels =None
def __init__(self,
img_folder = "../Generate_Individual_IDs_dataset/croppedImages",
labels = "labels.csv",
transforms = None
):
self.img_folder = img_folder
self.labels_path = os.path.join(img_folder,labels)
# load all image files, sorting them to
# ensure that they are aligned
self.imgs = list(sorted([i for i in os.listdir(self.img_folder) if (('.png' in i) or ('.jpg' in i) or ('.jpeg' in i))]))
self.transforms = transforms
def refresh(self):
self.imgs = list(sorted(os.listdir(os.path.join(self.root, self.img_folder))))
def __getitem__(self, idx):
# load images ad masks
if(isinstance(idx, str)):
try:
idx = int(idx)
except:
try:
if ((idx[-4:] == '.png') or (idx[-4:] == '.jpg')):
idx = self.imgs.index(idx[:-4]+'.jpg')
else:
idx = self.imgs.index(idx)
except:
print("invalid index")
idx = np.random.randint(low=0,high=len(self.imgs))
img_path = os.path.join(self.img_folder, self.imgs[idx])
img = Image.open(img_path).convert("RGB")
if not(self.transforms is None):
img = self.transforms(img)
if (self.labels is None):
fle = open(self.labels_path)
res = {}
for i in fle:
res[i.split(',')[0]] = i.split(',')[1]
fle.close()
self.labels = res
return img, int(self.labels[self.imgs[idx]].replace('\n','').replace(' ','').replace(',',''))
def __len__(self):
return len(self.imgs)
def __iter__(self,idx=0):
while(idx < len(self)):
idx+= 1
yield self[idx-1]
|
alnah005/raccoon_identification
|
Automatic_labeling_experiments/label_performance_measure.py
|
<filename>Automatic_labeling_experiments/label_performance_measure.py
# -*- coding: utf-8 -*-
"""
file: label_performance_measure.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-16T10:35:33.680Z-05:00
@last-modified: 2021-04-17T13:08:21.732Z-05:00
"""
# standard library
# 3rd party packages
# local source
import torch
from typing import List, Tuple, Any
import random
# labels1 = torch.load("train_real.pt")
# labels2 = torch.load("train_prediction.pt")
# labels1 = torch.tensor([1,1,1,1,2,2,2,3,3,4,4,4,4,5])
# labels2 = torch.tensor([2,2,3,1,1,2,1,3,4,1,1,2,3,1])
# labels1 = torch.tensor([1,1,1,2,2,2,3,3,4,2])
# labels2 = torch.tensor([2,3,1,1,1,3,2,2,1,3])
def match_label_with_predictions(chosen_class,eliminated_classes,error,labels1,labels2):
true_class_samples = labels2[labels1==chosen_class]
for eliminated_class in eliminated_classes:
true_class_samples = true_class_samples[true_class_samples != eliminated_class]
possible_class_labels = torch.unique(true_class_samples)
if (len(possible_class_labels) <= 0):
return eliminated_classes,error+len(labels2[labels1==chosen_class])
possible_class_counts = {class_number.item(): len(labels2[labels2==class_number]) for class_number in possible_class_labels}
within_class_counts = {class_number.item(): len(true_class_samples[true_class_samples==class_number]) for class_number in possible_class_labels}
class_count_difference = {class_number.item(): possible_class_counts[class_number.item()]-within_class_counts[class_number.item()] for class_number in possible_class_labels}
maximum1 = max(list(class_count_difference.values()))
possible_sorted_classes = sorted([(class_name,within_class_counts[class_name]) for class_name, count in class_count_difference.items() if count >= maximum1],reverse=True)
maximum2 = max([count for _,count in possible_sorted_classes])
possible_sorted_classes = [class_name for class_name,count in possible_sorted_classes if count >= maximum2]
possible_class:Tuple[Any,int] = possible_sorted_classes[-1]
eliminated_classes.append(possible_class)
assert len(list(set(eliminated_classes))) == len(eliminated_classes)
error += len(labels2[labels1==chosen_class]) - within_class_counts[possible_class]
return eliminated_classes, error
def calculate_error(labels1,labels2):
assert labels1.shape == labels2.shape
assert len(labels1.shape) == 1
class_labels = torch.unique(labels1)
for k in class_labels:
assert int == type(k.item())
class_labels2 = torch.unique(labels2)
for k in class_labels2:
assert int == type(k.item())
counts = {class_number.item(): len(labels1[labels1==class_number]) for class_number in class_labels}
eliminated_classes: List[Tuple[Any,int]] = []
error = 0
sampling_length = 100
while(len(counts) > 0):
maximum = max(list(counts.values()))
possible_predicted_classes = [class_name for class_name, count in counts.items() if count >= maximum]
sampling_errors_min = len(labels1)
eliminated_classes_min = [*eliminated_classes]
for k in range(sampling_length):
sorted_classes = [*possible_predicted_classes]
random.shuffle(sorted_classes)
current_error = 0
current_eliminated_classes = [*eliminated_classes]
for i in sorted_classes:
current_eliminated_classes, current_error = match_label_with_predictions(i,current_eliminated_classes,current_error,labels1,labels2)
if (current_error < sampling_errors_min):
sampling_errors_min = current_error
eliminated_classes_min = current_eliminated_classes
eliminated_classes = eliminated_classes_min
error += sampling_errors_min
counts = {class_name: class_count for class_name, class_count in counts.items() if class_name not in sorted_classes}
return error/len(labels1)
# calculate_error(labels1,labels2)
|
alnah005/raccoon_identification
|
Triplet_Loss_Framework/metric_learning.py
|
<gh_stars>0
# -*- coding: utf-8 -*-
"""
file: metric_learning.py
@author: Suhail.Alnahari
@description: Metric learning training file that runs based on [config.py] settings
@created: 2021-04-05T11:18:24.742Z-05:00
@last-modified: 2021-04-13T15:17:54.232Z-05:00
"""
# standard library
import logging
import os
# 3rd party packages
import pytorch_metric_learning.utils.logging_presets as logging_presets
from pytorch_metric_learning.utils.accuracy_calculator import AccuracyCalculator
from pytorch_metric_learning import testers
import numpy as np
import pytorch_metric_learning
# local source
from config_local import (
train_transform, val_transform, device,
torch, embedder,train_dataset, batch_size,num_epochs,
train_loader, miner, metric_loss, val_dataset,
feedback_every, feedback_callback, save_model_every_epochs,
checkpoint_loc
)
logging.getLogger().setLevel(logging.INFO)
logging.info("VERSION %s"%pytorch_metric_learning.__version__)
def get_all_embeddings(dataset, model):
# dataloader_num_workers has to be 0 to avoid pid error
# This only happens when within multiprocessing
tester = testers.BaseTester(dataloader_num_workers=0)
return tester.get_all_embeddings(dataset, model)
### compute accuracy using AccuracyCalculator from pytorch-metric-learning ###
def test_implem(train_set, test_set, model, accuracy_calculator):
with torch.no_grad():
train_embeddings, train_labels = get_all_embeddings(train_set, model)
test_embeddings, test_labels = get_all_embeddings(test_set, model)
print("Computing accuracy")
accuracies = accuracy_calculator.get_accuracy(test_embeddings,
train_embeddings,
test_labels,
train_labels,
False)
print("Validation set accuracy (Precision@1) = {}".format(accuracies["precision_at_1"]))
print("Validation set accuracies blob:\n {}".format(accuracies))
def test_model(train_set, test_set, model, epoch, data_device):
print("Computing validation set accuracy for epoch {}".format(epoch))
accuracy_calculator = AccuracyCalculator(include = ("precision_at_1",), k = 1)
test_implem(train_set, test_set, model, accuracy_calculator)
checkpoint_epoch = embedder.load()
if (checkpoint_epoch is None):
print("Starting training from scratch")
checkpoint_epoch = 0
for epoch in range(checkpoint_epoch,num_epochs):
epoch_loss = 0.
print("Starting epoch {}".format(epoch))
for i, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
embedder.zero_grad()
output = embedder(data)
hard_pairs = miner(output, target)
loss = metric_loss(output, target, hard_pairs)
epoch_loss += loss.item()
loss.backward()
embedder.optimize()
if i % feedback_every == 0:
print(feedback_callback(epoch, i, loss, miner))
if epoch % save_model_every_epochs ==0:
embedder.save(epoch)
print('Epoch {}, average loss {}'.format(epoch, epoch_loss/len(train_loader)))
test_model(train_dataset, val_dataset, embedder, epoch, device)
result_train_img, result_train_label = get_all_embeddings(train_dataset,embedder)
result_test_img, result_test_label = get_all_embeddings(val_dataset,embedder)
torch.save(result_train_img.cpu(),os.path.join(checkpoint_loc,'train_imgs.pt'))
torch.save(result_test_img.cpu(),os.path.join(checkpoint_loc,'test_imgs.pt'))
torch.save(result_train_label.cpu(),os.path.join(checkpoint_loc,'train_label.pt'))
torch.save(result_test_label.cpu(),os.path.join(checkpoint_loc,'test_label.pt'))
from sklearn.manifold import TSNE
tsne_model = TSNE(n_components=2, random_state=0,n_iter=10000,n_iter_without_progress=500,perplexity=35)
embedding = [embedder.forward(sample[0].unsqueeze(dim=0).cuda()).detach() for sample in val_dataset]
tsne = tsne_model.fit_transform(torch.cat(embedding,dim=0).cpu().detach().numpy())
torch.save(torch.tensor(tsne),os.path.join(checkpoint_loc,'tsne.pt'))
|
alnah005/raccoon_identification
|
Generate_Individual_IDs_dataset/get_images_from_frames_using_boxes.py
|
<reponame>alnah005/raccoon_identification
# -*- coding: utf-8 -*-
"""
file: get_images_from_frames_using_boxes.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-06T16:35:11.623Z-05:00
@last-modified: 2021-04-06T16:59:55.865Z-05:00
"""
# standard library
# 3rd party packages
# local source
import pandas as pd
import numpy as np
from PIL import Image
import os
imagesPath = "d:/Zoon_parent/Zooniverse/data/raccoons/images"
labelsPath = "d:/Zoon_parent/raccoon_identification/Generate_Individual_IDs_dataset/videoDataset.csv"
finalPath = "d:/Zoon_parent/raccoon_identification/Generate_Individual_IDs_dataset/croppedImages"
labels = pd.read_csv(labelsPath,header=None)
classLabels = {i:index for index,i in enumerate(np.unique(labels[6].values))}
f = open(os.path.join(finalPath,"labels.csv"),'w')
for index, i in enumerate(labels.values):
name,x1,x2,y1,y2,label,vid = i
image = Image.open(os.path.join(imagesPath,name))
cropped = image.crop((x1,x2,y1,y2))
cropped.save(os.path.join(finalPath,f'cropped_{index}_'+name))
f.write(f'cropped_{index}_'+name+','+str(classLabels[vid])+'\n')
f.close()
|
alnah005/raccoon_identification
|
Mega_detector_raccoon_transfer_learning/images_to_records.py
|
<reponame>alnah005/raccoon_identification<filename>Mega_detector_raccoon_transfer_learning/images_to_records.py
# -*- coding: utf-8 -*-
"""
file: images_to_records.py
@author: Suhail.Alnahari
@description:
@created: 2021-02-22T22:09:11.241Z-06:00
@last-modified: 2021-02-26T18:16:05.804Z-06:00
"""
# standard library
# 3rd party packages
# local source
import tensorflow as tf
from object_detection.utils import dataset_util
import json
import os
flags = tf.app.flags
flags.DEFINE_string('output_path', 'data', 'Path to output TFRecord')
FLAGS = flags.FLAGS
labels = {1: b'raccoon', 2:b'skunk',3:b'cat',4:b'human',5:b'fox',6:b'other'}
def create_tf_example(image_data):
"""Creates a tf.Example proto from sample cat image.
Args:
image_data: json input
Returns:
example: The created tf.Example.
"""
detections = image_data['detections']
height = 1080
width = 1920
scaledHeight = 500.0/1080
scaledWidth = 888.0/1920
filename = str.encode(image_data['file'])
image_format = b'jpg'
trainBool = True
try:
image_file = open(os.path.join(b'images_train',filename), 'rb')
encoded_image = image_file.read()
except:
try:
image_file = open(os.path.join(b'images_eval',filename), 'rb')
encoded_image = image_file.read()
trainBool = False
except:
print(filename)
assert False, "file was not found in either images_train or images_eval"
image_file.close()
xmins = [i['bbox'][0] / width for i in detections]
xmaxs = [i['bbox'][2] / width for i in detections]
ymins = [i['bbox'][1] / height for i in detections]
ymaxs = [i['bbox'][3] / height for i in detections]
classIndex = [i['category']+1 for i in detections]
classes_text = [labels[i] for i in classIndex]
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(int(height*scaledHeight)),
'image/width': dataset_util.int64_feature(int(width*scaledWidth)),
'image/filename': dataset_util.bytes_feature(filename),
'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_image),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classIndex),
}))
return tf_example, trainBool
def main(_):
with open('raccoon_volunteer_labels.json') as json_file:
examples = json.load(json_file)
trainIndex = 0
evalIndex = 0
for example in examples['images']:
try:
tf_example, trainBool = create_tf_example(example)
except:
continue
if (trainBool):
writer = tf.python_io.TFRecordWriter(os.path.join(FLAGS.output_path,'train-{0}-'.format(str(trainIndex).zfill(5))+'of-00001.tfrecord'))
trainIndex += 1
else:
writer = tf.python_io.TFRecordWriter(os.path.join(FLAGS.output_path,'eval-{0}-'.format(str(evalIndex).zfill(5))+'of-00001.tfrecord'))
evalIndex += 1
writer.write(tf_example.SerializeToString())
writer.close()
if __name__ == '__main__':
tf.app.run()
|
alnah005/raccoon_identification
|
Mega_detector_raccoon_transfer_learning_ll/convert_csv_to_json.py
|
# -*- coding: utf-8 -*-
"""
file: convert_csv_to_json.py
@author: Suhail.Alnahari
@description: File used to convert csv bounding box labels to JSON in the form of the JSON output from Microsoft's Mega detector
@created: 2021-02-15T10:40:00.541Z-06:00
@last-modified: 2021-03-02T15:45:40.168Z-06:00
"""
# standard library
# 3rd party packages
# local source
import pandas as pd
from dataclasses import dataclass
import json
import os
classLabel = {
'Raccoon':1,
'Skunk':2,
'Cat':3,
'Human':4,
'Fox':5,
'Other':6
}
labels = pd.read_csv('university-of-wyoming-raccoon-project-aggregated-for-retinanet.csv',header=None)
print(labels.keys())
labels = labels.values.tolist()
dicName: dict = {i[0].split('/')[-1]:[] for i in labels}
for i in labels:
dicName[i[0].split('/')[-1]].append(i)
dic: dict = {'images':[]}
listOfFiles = os.listdir('videoImages')
height = 1080
width = 1920
for fileName in dicName:
if (fileName in listOfFiles):
res = {'detections':[],'file':"/content/drive/MyDrive/Zooniverse/videoImages/"+fileName,'max_detection_conf':1.00}
for k in dicName[fileName]:
xmins = k[1] / width
xmaxs = k[3] / width
ymins = k[2] / height
ymaxs = k[4] / height
detection = {'bbox': [xmins,ymins,abs(xmaxs-xmins),abs(ymaxs-ymins)],'category':str(classLabel[k[-1]]),'conf':1.00}
res['detections'].append(detection)
dic['images'].append(res)
dic["detection_categories"] = {
"1": "raccoon",
"2": "skunk",
"3": "cat",
"4": "human",
"5": "fox",
"6": "other"}
dic["info"] = {
"detection_completion_time": "2021-03-02 20:01:22",
"format_version": "1.0"
}
with open('raccoon_true.json', 'w') as outfile:
json.dump(dic, outfile,indent=1)
|
alnah005/raccoon_identification
|
Automatic_labeling_experiments/clustering.py
|
# -*- coding: utf-8 -*-
"""
file: clustering.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-08T17:50:09.624Z-05:00
@last-modified: 2021-04-14T14:43:13.828Z-05:00
"""
# standard library
# 3rd party packages
# local source
import time
import matplotlib.pyplot as plt
import numpy as np
from typing import Dict
from sklearn.cluster import AgglomerativeClustering
from sklearn.neighbors import kneighbors_graph
from sklearn.metrics import silhouette_score
import torch
from scipy.sparse import csr_matrix
from tqdm import tqdm
import pandas as pd
from scipy import stats
import random
import os
def to_one_hot(y, n_dims=None):
""" Take integer tensor with n dims and convert it to 1-hot representation with n+1 dims. """
y_tensor = y.view(-1, 1)
n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1
y_one_hot = torch.zeros(y_tensor.size()[0], n_dims)
for i in range(y_tensor.size()[0]):
y_one_hot[i,y.view(-1,)[i]] = 1
return y_one_hot
def read_checkpoint_config(ckpt_loc="/home/fortson/alnah005/raccoon_identification/Triplet_Loss_Framework/experiment",config_name='config.txt'):
f = open(os.path.join(ckpt_loc,config_name))
lines = f.readlines()
f.close()
assert len(lines) > 0
return os.path.join(ckpt_loc,lines[-1].replace('\n',''))
checkpoint_loc = read_checkpoint_config()
print("loading from "+checkpoint_loc)
X = torch.load(os.path.join(checkpoint_loc, "test_imgs.pt"))
# Graph = torch.load(os.path.join(checkpoint_loc,"test_label.pt"))
# one_hot = to_one_hot(Graph)
# labels_connection = one_hot@one_hot.T
# for i in range(labels_connection.shape[0]):
# labels_connection[i,i] = 0
# labels_connection = csr_matrix(labels_connection)
# from sklearn.manifold import TSNE
# tsne_model = TSNE(n_components=2, random_state=0,n_iter=5000,n_iter_without_progress=500,perplexity=35)
# tsne = tsne_model.fit_transform(X.cpu().detach().numpy())
tsne = torch.load(os.path.join(checkpoint_loc, "tsne.pt"))
# Create a graph capturing local connectivity. Larger number of neighbors
# will give more homogeneous clusters to the cost of computation
# time. A very large number of neighbors gives more evenly distributed
# cluster sizes, but may not impose the local manifold structure of
# the data
# knn_graph = kneighbors_graph(X, 30, include_self=False)
conn = ["none","labels"]
sil: Dict[str,Dict[int,Dict[str,float]]] = {}
for conn_index, connectivity in tqdm(enumerate([None]),desc="Connectivity\n\n\n"):
sil[conn[conn_index]] = {}
for n_clusters in tqdm((3,5,7,8,9,10,11,12,15,17,20,21,23,24,25,26,27,28,29,30),desc=f"\t {conn[conn_index]} num_cluster\n\n"):
sil[conn[conn_index]][n_clusters] = {}
plt.figure(figsize=(10, 4))
for index, linkage in tqdm(enumerate(('average',
'complete',
'ward',
'single')),desc=f"\t\t {n_clusters} linkage \n"):
plt.subplot(1, 4, index + 1)
model = AgglomerativeClustering(linkage=linkage,
connectivity=connectivity,
n_clusters=n_clusters)
t0 = time.time()
model.fit(X)
elapsed_time = time.time() - t0
sil[conn[conn_index]][n_clusters][linkage] = silhouette_score(X, model.labels_, metric = 'euclidean')
plt.scatter(tsne[:, 0], tsne[:, 1], c=model.labels_,
cmap=plt.cm.nipy_spectral)
plt.title('linkage=%s\n(time %.2fs)' % (linkage, elapsed_time),
fontdict=dict(verticalalignment='top'))
plt.axis('equal')
plt.axis('off')
plt.subplots_adjust(bottom=0, top=.83, wspace=0,
left=0, right=1)
plt.suptitle('n_cluster=%i, connectivity=%r' %
(n_clusters, connectivity is not None), size=17)
plt.savefig(os.path.join(checkpoint_loc, f"{conn[conn_index]}_{n_clusters}_{index}_{linkage}.png"))
results = {i:None for i in sil.keys()}
for i in sil.keys():
result = []
for j in sil[i].keys():
cluster_size = [j]
for k in sil[i][j].keys():
cluster_size.append(sil[i][j][k])
result.append(cluster_size+[np.average(cluster_size[1:])])
results[i] = pd.DataFrame(np.asarray(result),columns=["cluster_size"]+list(sil[i][j].keys())+['coeff_avg'])
results[i].to_csv(os.path.join(checkpoint_loc, f"{i}.csv"),index=False)
optimal_cluster_sizes = [int(results[i]['cluster_size'][results[i]['coeff_avg'].argmax()]) for i in sil.keys()]
X_train = torch.load(os.path.join(checkpoint_loc, "train_imgs.pt"))
clus = random.choice(optimal_cluster_sizes)
model = AgglomerativeClustering(
linkage='ward',
connectivity=None,
n_clusters=clus)
model.fit(torch.cat((X_train,X)))
new_train_labels = model.labels_
torch.save(torch.tensor(new_train_labels[:len(X_train)]),os.path.join(checkpoint_loc, "train_clustering_labels.pt"))
torch.save(torch.tensor(new_train_labels[len(X_train):]),os.path.join(checkpoint_loc, "test_clustering_labels.pt"))
|
alnah005/raccoon_identification
|
measuring_fine_tuning/box_compare.py
|
# -*- coding: utf-8 -*-
"""
file: box_compare.py
@author: Suhail.Alnahari
@description: File used to analyze the differences between Volunteer labels and Microsoft's Mega Detector
@created: 2021-02-15T10:20:13.627Z-06:00
@last-modified: 2021-03-15T12:42:02.792Z-05:00
"""
# standard library
# 3rd party packages
# local source
import json
from dataclasses import dataclass
from tqdm import tqdm
fileName1 = 'raccoon_eval_mega_transfer_2.json'
fileName2 = 'raccoon_volunteer_labels.json'
matchesOutput: str = 'numbers_with_finetuning.csv'
boxAccOutput: str = 'box_acc_with_finetuning.csv'
swapBool = True
def convert_y1_x1_y2_x2(tf_coords):
return [tf_coords[0]*1920, tf_coords[1]*1080, (tf_coords[0]+tf_coords[2])*1920,(tf_coords[1]+tf_coords[3])*1080]
def sorted_enumerate(seq):
args = [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
values = sorted(seq)
result = []
for i in range(len(seq)):
result.append((args[i],values[i]))
return result
@dataclass
class Detection:
def __init__(self, detection,convert):
self.bbox = detection['bbox']
if (convert):
self.bbox = convert_y1_x1_y2_x2(self.bbox)
self.category = detection['category']
self.conf = detection['conf']
def __post_init__(self):
assert isinstance(self.bbox, list)
assert isinstance(self.conf, float)
@dataclass
class ImageDetection:
def __init__(self,detections,name,confidence,convertBox=False):
self.detections = [Detection(i,convertBox) for i in detections]
self.fileName = name.split('/')[-1]
self.maxConfidence = confidence
def __post_init__(self):
assert isinstance(self.detections, list)
assert isinstance(self.fileName, str)
assert 'jpg' in self.fileName
with open(fileName1) as json_file:
data = json.load(json_file)
with open(fileName2) as json_file:
data2 = json.load(json_file)
imagePreds = [ImageDetection(i['detections'],i['file'],i['max_detection_conf'],convertBox=True) for i in data['images']]
imageDict = {i.fileName: i for i in imagePreds}
imagePreds2 = [ImageDetection(i['detections'],i['file'],i['max_detection_conf']) for i in data2['images']]
imageDict2 = {i.fileName: i for i in imagePreds2}
def compare_numbers(detections1,detections2):
return abs(len(detections1)-len(detections2))
def Euclidean(point1,point2):
assert(len(point1)==2)
assert(len(point2)==2)
return (abs(point2[1]-point1[1])**2 + abs(point2[0]-point1[0])**2)**0.5
def coordsToCenter(dets):
return [((d.bbox[2]+d.bbox[0])/2, (d.bbox[3]+d.bbox[1])/2) for d in dets]
def removeCenter(center,c_prefs):
return [[(a[0],a[1]) for a in k if a[0] != center] for k in c_prefs]
def matchClosestCenters(c_prefs):
selected = [0 for i in range(len(c_prefs))]
center1 = 0
center2 = 0
distance = 100000000000
result = []
while sum(selected) < len(c_prefs):
for i in range(len(selected)):
if (selected[i] == 0):
if (len(c_prefs[i]) > 0):
if (distance > c_prefs[i][0][1]):
center1 = i
center2 = c_prefs[i][0][0]
distance = c_prefs[i][0][1]
else:
selected[i] = 1
result.append((i,None))
if (selected[center1]==0):
result.append((center1,center2))
distance = 100000000000
selected[center1] = 1
c_prefs = removeCenter(center2,c_prefs)
return result
def getCenterPairs(det1,det2):
centers1 = coordsToCenter(det1)
centers2 = coordsToCenter(det2)
rev = False
if (len(centers1) < len(centers2)):
temp = centers1
centers1 = [i for i in centers2]
centers2 = temp
rev = True
global swapBool
if (swapBool):
print("Reversed order. Make sure this doesn't affect final result.")
swapBool = False
center_pref_distance = [None for i in range(len(centers1))]
for index,i in enumerate(centers1):
distances = [Euclidean(i,j) for j in centers2]
center_pref_distance[index] = sorted_enumerate(distances)
centerPairsIndexes = matchClosestCenters(center_pref_distance)
result = []
for i in range(len(centerPairsIndexes)):
c1,c2 = centerPairsIndexes[i]
if c1 is None and c2 is None:
assert(False)
elif c2 is None:
result.append((centers1[c1],None))
elif c1 is None:
result.append((None,centers2[c2]))
else:
result.append((centers1[c1],centers2[c2]))
return result
def compare_center_distance(detections1,detections2,radius,distanceMeasure):
mismatches = 0
pairs = getCenterPairs(detections1,detections2)
for i in pairs:
if (i[0] is None) or (i[1] is None):
mismatches += 1
continue
distance = distanceMeasure(i[0],i[1])
if (distance > radius):
mismatches += 1
return mismatches
def compare_predictions(detections1,detections2,threshold=0.,radius=50,distanceMeasure = Euclidean):
det1 = [i for i in detections1 if i.conf > threshold]
det2 = [i for i in detections2 if i.conf > threshold]
numbersMatch = compare_numbers(det1,det2)
box_accuracy = compare_center_distance(det1,det2,radius,distanceMeasure)
return numbersMatch,box_accuracy
import sys
def progressbar(it, prefix="", size=60, file=sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
file.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
file.write("\n")
file.flush()
import numpy as np
x = np.arange(0, 1, 0.025)
y = np.arange(5, 2000, 25)
xx, yy = np.meshgrid(x, y)
z1 = np.zeros(xx.shape)
z2 = np.zeros(xx.shape)
for i in progressbar(range(len(y))):
for j in range(len(x)):
numbersTotal = 0
box_accuracyTotal = 0
indexer = imageDict
if (len(imageDict) > len(imageDict2)):
indexer = imageDict2
for k in indexer:
numbers, box_accuracy = compare_predictions(imageDict[k].detections,imageDict2[k].detections,threshold=xx[i,j],radius=yy[i,j])
numbersTotal += numbers
box_accuracyTotal += box_accuracy
z1[i,j] = numbersTotal
z2[i,j] = box_accuracyTotal
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure()
h1 = plt.contourf(x,y,z1)
plt.show()
fig.savefig(matchesOutput.split('.')[0])
pd.DataFrame(data=np.concatenate((y.reshape(-1,1),z1),axis=1),columns=np.concatenate((np.asarray([0]),x))).to_csv(matchesOutput,index=False)
fig = plt.figure()
h2 = plt.contourf(x,y,z2)
plt.show()
fig.savefig(boxAccOutput.split('.')[0])
pd.DataFrame(data=np.concatenate((y.reshape(-1,1),z2),axis=1),columns=np.concatenate((np.asarray([0]),x))).to_csv(boxAccOutput,index=False)
print(1)
|
alnah005/raccoon_identification
|
Automatic_labeling_experiments/get_error_from_experiments.py
|
<reponame>alnah005/raccoon_identification
# -*- coding: utf-8 -*-
"""
file: get_error_from_experiments.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-16T14:19:12.828Z-05:00
@last-modified: 2021-04-17T13:08:13.615Z-05:00
"""
# standard library
import os
# 3rd party packages
import torch
# local source
import label_performance_measure as lpm
base_dir = './joblib'
experiments_dirs = [direc for direc in os.listdir(base_dir) if 'experiment' == direc[:len('experiment')]]
numbers = sorted([int(i.split('_')[1]) for i in experiments_dirs])
_, labels1_train = torch.load("./processed/training.pt")
_, labels1_test = torch.load("./processed/test.pt")
labels1 = torch.cat((labels1_train,labels1_test))
final_errors = []
comparing_accross_time: lpm.List[lpm.List[int]] = []
labels_size = []
labels_before = None
for i in numbers:
cwd = os.path.join(base_dir,f"experiment_{i}")
pred_train_labels = torch.load(os.path.join(cwd,'train_clustering_labels.pt'))
pred_test_labels = torch.load(os.path.join(cwd,'test_clustering_labels.pt'))
labels2 = torch.cat((pred_train_labels,pred_test_labels))
labels_size.append(len(torch.unique(labels2)))
final_errors.append(lpm.calculate_error(labels1,labels2))
if not(labels_before is None):
comparing_accross_time.append(lpm.calculate_error(labels_before,labels2))
labels_before = labels2.detach()
print("\n".join([str(elem) for elem in final_errors]))
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.plot(np.arange(len(final_errors)),np.asarray(labels_size))
plt.show()
plt.figure()
plt.plot(np.arange(len(final_errors)),np.asarray(final_errors),label='Isomerphic Sim')
plt.legend()
plt.show()
print("\n".join([str(elem) for elem in comparing_accross_time]))
plt.figure()
plt.plot(np.arange(len(comparing_accross_time)),np.asarray(comparing_accross_time),label='Isomerphic Sim')
plt.legend()
plt.show()
# lpm.calculate_error(torch.tensor([1,2,3,3,4,5,6]),torch.tensor([1,2,3,3,4,5,6]))
|
alnah005/raccoon_identification
|
measuring_fine_tuning/convert_csv_to_json.py
|
# -*- coding: utf-8 -*-
"""
file: convert_csv_to_json.py
@author: Suhail.Alnahari
@description: File used to convert csv bounding box labels to JSON in the form of the JSON output from Microsoft's Mega detector
@created: 2021-02-15T10:40:00.541Z-06:00
@last-modified: 2021-02-19T14:00:39.384Z-06:00
"""
# standard library
# 3rd party packages
# local source
import pandas as pd
from dataclasses import dataclass
import json
classLabel = {
'Raccoon':0,
'Skunk':1,
'Cat':2,
'Human':3,
'Fox':4,
'Other':5
}
labels = pd.read_csv('university-of-wyoming-raccoon-project-aggregated-for-retinanet.csv',header=None)
print(labels.keys())
labels = labels.values.tolist()
dicName: dict = {i[0].split('/')[-1]:[] for i in labels}
for i in labels:
dicName[i[0].split('/')[-1]].append(i)
dic: dict = {'images':[]}
for fileName in dicName:
res = {'detections':[],'file':fileName,'max_detection_conf':1.00}
for k in dicName[fileName]:
detection = {'bbox': k[1:-1],'category':classLabel[k[-1]],'conf':1.00}
res['detections'].append(detection)
dic['images'].append(res)
with open('raccoon_true.json', 'w') as outfile:
json.dump(dic, outfile,indent=1)
|
alnah005/raccoon_identification
|
Generate_Individual_IDs_dataset/raccoon_ids_script_from_videos_only.py
|
# -*- coding: utf-8 -*-
"""
file: raccoon_ids_script.py
@author: Suhail.Alnahari
@description:
@created: 2021-04-06T10:48:08.072Z-05:00
@last-modified: 2021-04-06T16:50:40.059Z-05:00
"""
# standard library
# 3rd party packages
# local source
import pandas as pd
import numpy as np
from typing import List, Dict
import datetime
class Frame:
def __init__(self, boxes, classifications, name, video):
self.boxes: List[List[float]] = boxes
self.classifications: List[str] = classifications
self.name: str = name
self.video: str = video
def _oneAnimalPerFrame(self) -> bool:
return len(self.classifications) == 1
def oneAnimalPerFrameGetter(self) -> str:
if self._oneAnimalPerFrame():
return self.classifications[-1]
return ""
def getDominantAnimal(self) -> str:
if (len(self.classifications) == 0):
return ""
def most_frequent(lst: List[str]) -> str:
counter = 0
num = lst[0]
for i in lst:
curr_frequency = lst.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
return most_frequent(self.classifications)
def addLabels(self,box: List[float], className: str):
assert len(box) == 4
assert len(className) > 0
self.boxes.append(box)
self.classifications.append(className)
def __len__(self) -> int:
return len(self.classifications)
def __repr__(self) -> str:
return f"{self.name} has {len(self.classifications)} classifications with {self.getDominantAnimal()} dominant"
def __str__(self) -> str:
return f"{self.name} has {len(self.classifications)} classifications with {self.getDominantAnimal()} dominant"
class Video:
def __init__(self, frames: List[Frame], name: str,nameFormat: str = '%m%d%Y'):
for i in frames:
assert i.video == name
self.frames: List[Frame] = frames
self.name: str = name
self.getDateFromName(nameFormat)
def isOneSpeciesVideo(self) -> bool:
animals: Dict[str,int]= {}
for frame in self.frames:
if (frame.oneAnimalPerFrameGetter() != ""):
if (frame.oneAnimalPerFrameGetter() in animals.keys()):
animals[frame.oneAnimalPerFrameGetter()] += 1
else:
animals[frame.oneAnimalPerFrameGetter()] = 1
# print(animals)
return len(animals.keys()) == 1
def addFrame(self, frame: Frame):
assert frame.video == self.name
if not(frame.name in [f.name for f in self.frames]):
self.frames.append(frame)
def getDominantSpecies(self) -> str:
if (len(self.frames) == 0):
return ""
def most_frequent(lst: List[str]) -> str:
counter = 0
num = lst[0]
for i in lst:
curr_frequency = lst.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
species: List[str] = []
for frame in self.frames:
species.append(frame.getDominantAnimal())
return most_frequent(species)
def getAllSpecies(self) -> List:
if (len(self.frames) == 0):
return []
species: List[str] = []
for frame in self.frames:
species.append(frame.getDominantAnimal())
return np.unique(species)
def __len__(self):
return len(self.frames)
def getDateFromName(self,nameFormat):
fileName = self.name.split('/')[-1]
date = fileName.split('_')[-3]
# print(date)
self.date = datetime.datetime.strptime(date, nameFormat)
def __repr__(self) -> str:
result = ''
for f in self.frames:
for i in range(len(f)):
result += ','.join([f.name.split('/')[-1],*[str(b) for b in f.boxes[i]],f.classifications[i]])
result += '\n'
return result
def __str__(self) -> str:
result = ''
for f in self.frames:
for i in range(len(f)):
result += ','.join([f.name.split('/')[-1],*[str(b) for b in f.boxes[i]],f.classifications[i],self.name.split('/')[-1]])
result += '\n'
return result
labelPath = "d:/Zoon_parent/Zooniverse/data/raccoons/university-of-wyoming-raccoon-project-aggregated-for-retinanet.csv"
# labelPath = 'test.csv'
labels = pd.read_csv(labelPath,header=None)
labels['videos'] = labels[0].apply(lambda name: '_'.join(name.split('_')[:-1]))
videoList: Dict[str,Video] = {}
frameList: Dict[str, Frame] = {}
for i in labels.values:
if not(i[-1] in videoList.keys()):
videoList[i[-1]] = Video([],i[-1])
if not(i[0] in frameList.keys()):
frameList[i[0]] = Frame([],[],i[0],i[-1])
videoList[i[-1]].addFrame(frameList[i[0]])
frameList[i[0]].addLabels(i[1:5],i[5])
print(f"Number of videos in this dataset: {len(videoList)}")
datasetSize = 0
for i in videoList.keys():
datasetSize += len(videoList[i])
print(f"Number of frames in this dataset: {datasetSize}")
datasetClassificationSize = 0
for i in frameList.keys():
datasetClassificationSize += len(frameList[i])
print(f"Number of classifications in this dataset: {datasetClassificationSize}")
datasetClassificationSizeVideos = 0
for i in videoList.keys():
for f in videoList[i].frames:
datasetClassificationSizeVideos += len(f)
print(f"Number of classifications in this dataset from videos: {datasetClassificationSizeVideos}")
oneSpeciesVideos: Dict[str,Video] = {}
for video in videoList.keys():
if (videoList[video].isOneSpeciesVideo()):
oneSpeciesVideos[video] = videoList[video]
species: Dict[str,str] = {}
for video in oneSpeciesVideos:
species[video] = videoList[video].getDominantSpecies()
onlyTheseSpecies = ['raccoon']
filteredVideos: Dict[str,str] = {}
for i in species.keys():
if (species[i].lower() in onlyTheseSpecies):
filteredVideos[i] = species[i]
# print(filteredVideos)
print(f"Number of videos that have one species of the following categories {onlyTheseSpecies}: {len(filteredVideos)}")
datasetSize = 0
for i in filteredVideos:
datasetSize += len(videoList[i])
print(f"Number of frames that have one species of the following categories {onlyTheseSpecies}: {datasetSize}")
print(f"average number of frames per video: {sum([len(videoList[i]) for i in filteredVideos])/len(filteredVideos.keys())}")
selectedVideos = [videoList[i] for i in filteredVideos]
selectedVideos = sorted(selectedVideos,key=lambda k: k.date)
selectedVideos = [selected for selected in selectedVideos]
selectedVideosWithThresh = [i.name for i in selectedVideos]
before = len(selectedVideosWithThresh)
after = 0
while(before != after):
result = []
before = len(selectedVideosWithThresh)
deleted = False
for i in range(len(selectedVideos)-1):
if (abs((selectedVideos[i].date-selectedVideos[i+1].date).days) < 2):
if (len(selectedVideos[i]) > len(selectedVideos[i+1])):
if (not(deleted)):
selectedVideosWithThresh.remove(selectedVideos[i+1].name)
else:
if (not(deleted)):
selectedVideosWithThresh.remove(selectedVideos[i].name)
deleted = True
result.append(abs((selectedVideos[i].date-selectedVideos[i+1].date).days))
selectedVideos = [videoList[selected] for selected in selectedVideosWithThresh]
after = len(selectedVideosWithThresh)
# import matplotlib.pyplot as plt
# n, bins, patches = plt.hist(x=[len(videoList[i.name]) for i in selectedVideos], bins='auto', color='#0504aa',
# alpha=0.7, rwidth=0.85)
# plt.grid(axis='y', alpha=0.75)
# plt.xlabel('Number of frames')
# plt.ylabel('Number of videos')
# plt.title('Number of frames for videos where only one raccoon was identified')
# maxfreq = n.max()
# # Set a clean upper y-axis limit.
# plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
# plt.show()
# import matplotlib.pyplot as plt
# n, bins, patches = plt.hist(x=[len(videoList[i]) for i in filteredVideos], bins='auto', color='#0504aa',
# alpha=0.7, rwidth=0.85)
# plt.grid(axis='y', alpha=0.75)
# plt.xlabel('Number of frames')
# plt.ylabel('Number of videos')
# plt.title('Number of frames for videos where only one raccoon was identified')
# maxfreq = n.max()
# # Set a clean upper y-axis limit.
# plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
# plt.show()
# import matplotlib.pyplot as plt
# n, bins, patches = plt.hist(x=result, bins='auto', color='#0504aa',
# alpha=1, rwidth=0.85)
# plt.grid(axis='y', alpha=0.75)
# plt.xlabel('Running difference between dates starting from the earliest date')
# plt.ylabel('Number of videos')
# plt.title('Number of videos where only one raccoon was identified')
# maxfreq = n.max()
# # Set a clean upper y-axis limit.
# plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
# plt.show()
fle = open("videoDataset.csv",'w')
for i in selectedVideos:
fle.write(str(i))
fle.close()
# for i in videoList.keys():
# print(f"{i} has these species {videoList[i].getAllSpecies()}")
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut8.py
|
# chapter Matplotlib Plotting
'''
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the plot function.
'''
# Draw a line in a diagram from position (1, 3) to position (8, 10):
import matplotlib.pyplot as plt
import numpy as r
import sys
x=r.array([1,9,])
y=r.array([4,10])
plt.plot(x,y)
plt.show()
'''
Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'.
'''
x=r.array([3,10])
y=r.array([0,34])
plt.plot(x,y,'o')
plt.show()
'''
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both axis.
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10):f
'''
x=r.array([1,2,4,9])
y=r.array([3,6,8,10])
plt.plot(x,y,label="red")
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
'''
Default X-Points
If we do not specify the points in the x-axis, they will get the default values 0, 1, 2, 3, (etc. depending on the length of the y-points.
So, if we take the same example as above, and leave out the x-points, the diagram will look like this:
'''
# Plotting without x-points:
ypoints=r.array([0,2,3,5,6,7,99])
plt.plot(ypoints)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
# CHAPTER Matplotlib Markers
'''
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
'''
x=r.array([0,3,5,6,8,9])
y=r.array([2,4,6,7,8,10])
plt.plot(x,y,marker="*")
plt.show()
'''
Marker Reference
You can choose any of these markers:
Marker Description
'o' Circle
'*' Star
'.' Point
',' Pixel
'x' X
'X' X (filled)
'+' Plus
'P' Plus (filled)
's' Square
'D' Diamond
'd' Diamond (thin)
'p' Pentagon
'H' Hexagon
'h' Hexagon
'v' Triangle Down
'^' Triangle Up
'<' Triangle Left
'>' Triangle Right
'1' Tri Down
'2' Tri Up
'3' Tri Left
'4' Tri Right
'|' Vline
'_' Hline
'''
'''
Format Strings fmt
You can use also use the shortcut string notation parameter to specify the marker.
This parameter is also called fmt, and is written with this syntax:
marker|line|color
Example
Mark each point with a circle:
'''
x=r.array([3,5,5,6,7,8])
y=r.array([1,3,5,6,7,8])
plt.plot(x,y,'-.r')
plt.show()
'''
The marker value can be anything from the Marker Reference above.
The line value can be one of the following:
Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
Note: If you leave out the line value in the fmt parameter, no line will be plottet.
'''
'''
Color Reference
Color Syntax Description
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
'''
'''
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:
'''
x=r.array([1,3,4,5,9,5])
y=r.array([0,3,6,8,8])
plt.plot(x,marker='o',ms='17')
plt.show()
'''
Marker Color
You can use the keyword argument markeredgecolor or the shorter mec to set the color of the edge of the markers:
Example
Set the EDGE color to red:
'''
x=r.array([2,3,5,6])
y=r.array('[0,3,5,6,8]')
plt.plot(x,marker='*',ms=34,mec='r')
plt.show()
'''
You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the markers:
Example
Set the FACE color to red:
'''
x=r.array([1,3,5,6])
y=r.array([2,3,5,6])
plt.plot(x,marker='*',ms=34,mfc='r')
plt.show()
'''
# Use both the mec and mfc arguments to color of the entire marker:
# Example
# Set the color of both the edge and the face to red:
'''
import matplotlib.pyplot as plt
import numpy as r
y=r.array([0,4,6,7,7,8])
plt.plot(y,marker='*',ms=30,mec='r',mfc='r')
plt.show()
'''
You can also use Hexadecimal color values:
Example
Mark each point with a beautiful green color:
...
plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')
...
'''
import matplotlib.pyplot as plt
import numpy as np
x=np.array([1,2,3,4,5,6,5,7])
y=np.array([1,2,4,5,5,6,])
plt.plot(y,ms=34,marker='*',mec='hotpink',mfc="hotpink",linestyle=':')
plt.show()
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut12_Scattter_plot.py
|
import matplotlib.pyplot as plt
import numpy as r
x=r.array([3,3,5,23])
y=r.array([3,5,6,73])
plt.scatter(x,y,color="hotpink")
x=r.array([3,3,5,6,7,7,22])
y=r.array([3,5,6,7,7,8,22])
plt.scatter(x,y,color="#88c999")
plt.show()
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut4.py
|
# chapter strings str = "harry cmd gather hacking file_exe.py file "
for x in "banana":
print(x)
p= " print free is text "
if "exellent " not in p:
print("yes,'exellent in NOT in p " )
else:
print("No, 'exellent' is NOT in p " )
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut2.py
|
# chapter " python module "
# how to create module : create a funtion by define my funtion and save it . how to use by importing that file extension and then use file name as
# import mymodule
# variable_name.funtion_name then print like
# or you can be like import myclass as gtx
from mymodule import myclass
a = myclass.agent1["majority"]
print(a)
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/tut1+machine_learning.py
|
<filename>codeMania-python-AI-Machine-learning/tut1+machine_learning.py
# mean median mode
'''
what can we learn from looking at a group of numbers?
In Machine Learning (and in mathematics) there are often three values that interests us:
Mean - The average value
Median - The mid point value
Mode - The most common value
Example: We have registered the speed of 13 cars:
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
'''
import numpy as r
from scipy import stats
speed= [32,35,232,323,434,544,644,644,644]
o=r.median(speed) #mean or for mode use it import stats from scipy
print(o)
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/tut7_linear_regreation.py
|
<filename>codeMania-python-AI-Machine-learning/tut7_linear_regreation.py
'''
Machine Learning - Linear Regression
Regression
The term regression is used when you try to find the relationship between variables.
In Machine Learning, and in statistical modeling, that relationship is used to predict the outcome of future events.
Linear Regression
Linear regression uses the relationship between the data-points to draw a straight line through all them.
This line can be used to predict future values.
'''
'''
In Machine Learning, predicting the future is very important.
How Does it Work?
Python has methods for finding a relationship between data-points and to draw a line of linear regression. We will show you how to use these methods instead of going through the mathematic formula.
In the example below, the x-axis represents age, and the y-axis represents speed. We have registered the age and speed of 13 cars as they were passing a tollbooth. Let us see if the data we collected could be used in a linear regression:
'''
import matplotlib.pyplot as plt
from scipy import stats
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
slope, intercept, r,p ,std_err=stats.linregress(x, y)
def myfun(x):
return slope * x + intercept
mymodel=list(map(myfun,x))
plt.scatter(x,y)
plt.plot(x,mymodel)
plt.show()
'''
Example Explained
Import the modules you need.
You can learn about the Matplotlib module in our Matplotlib Tutorial.
You can learn about the SciPy module in our SciPy Tutorial.
import matplotlib.pyplot as plt
from scipy import stats
Create the arrays that represent the values of the x and y axis:
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
Execute a method that returns some important key values of Linear Regression:
slope, intercept, r, p, std_err = stats.linregress(x, y)
Create a function that uses the slope and intercept values to return a new value. This new value represents where on the y-axis the corresponding x value will be placed:
def myfunc(x):
return slope * x + intercept
Run each value of the x array through the function. This will result in a new array with new values for the y-axis:
mymodel = list(map(myfunc, x))
Draw the original scatter plot:
plt.scatter(x, y)
Draw the line of linear regression:
plt.plot(x, mymodel)
Display the diagram:
plt.show()
R for Relationship
It is important to know how the relationship between the values of the x-axis and the values of the y-axis is, if there are no relationship the linear regression can not be used to predict anything.
This relationship - the coefficient of correlation - is called r.
The r value ranges from -1 to 1, where 0 means no relationship, and 1 (and -1) means 100% related.
Python and the Scipy module will compute this value for you, all you have to do is feed it with the x and y values.
Example
How well does my data fit in a linear regression?
from scipy import stats
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
slope, intercept, r, p, std_err = stats.linregress(x, y)
print(r)
Note: The result -0.76 shows that there is a relationship, not perfect, but it indicates that we could use linear regression in future predictions.
Predict Future Values
Now we can use the information we have gathered to predict future values.
Example: Let us try to predict the speed of a 10 years old car.
To do so, we need the same myfunc() function from the example above:
def myfunc(x):
return slope * x + intercept
'''
from scipy import stats
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
slope , intercept , r ,p ,std_err=stats.linregress(x, y)
def myfun(x):
return slope* x + intercept
speed=myfun(10)
print(speed)
'''
Predict Future Values
Now we can use the information we have gathered to predict future values.
Example: Let us try to predict the speed of a 10 years old car.
To do so, we need the same myfunc() function from the example above:
def myfunc(x):
return slope * x + intercept
Example
Predict the speed of a 10 years old car:
from scipy import stats
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
slope, intercept, r, p, std_err = stats.linregress(x, y)
def myfunc(x):
return slope * x + intercept
speed = myfunc(10)
print(speed)
The example predicted a speed at 85.6, which we also could read from the diagram:
Bad Fit?
Let us create an example where linear regression would not be the best method to predict future values.
Example
These values for the x- and y-axis should result in a very bad fit for linear regression:
import matplotlib.pyplot as plt
from scipy import stats
x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]
y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]
slope, intercept, r, p, std_err = stats.linregress(x, y)
def myfunc(x):
return slope * x + intercept
mymodel = list(map(myfunc, x))
plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()
Result:
'''
'''
And the r for relationship?
Example
You should get a very low r value.
import numpy
from scipy import stats
x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]
y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]
slope, intercept, r, p, std_err = stats.linregress(x, y)
print(r)
The result: 0.013 indicates a very bad relationship, and tells us that this data set is not suitable for linear regression.
'''
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut5.py
|
<gh_stars>0
# from a keyword that you want to import function of a particular class object and dict.tupple.lists ecxtc # note module_name.variable_name for creating module syntax.
from mymodule import myclass
import platform
print(myclass.agent3["age"])
print(platform.system)
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/tut4_data_distribution.py
|
'''
Machine Learning - Data Distribution
Data Distribution
Earlier in this tutorial we have worked with very small amounts of data in our examples, just to understand the different concepts.
In the real world, the data sets are much bigger, but it can be difficult to gather real world data, at least at an early stage of a project.
How Can we Get Big Data Sets?
To create big data sets for testing, we use the Python module NumPy, which comes with a number of methods to create random data sets, of any size.
Example
Create an array containing 250 random floats between 0 and 5:
import numpy
x = numpy.random.uniform(0.0, 5.0, 250)
print(x)
'''
import numpy as r
e=r.random.uniform(0.5,5,250)
print(e)
'''
Histogram
To visualize the data set we can draw a histogram with the data we collected.
We will use the Python module Matplotlib to draw a histogram.
Learn about the Matplotlib module in our Matplotlib Tutorial.
Example
Draw a histogram:
import numpy
import matplotlib.pyplot as plt
x = numpy.random.uniform(0.0, 5.0, 250)
plt.hist(x, 5)
plt.show()
note: The array values are random numbers and will not show the exact same result on your computer.
'''
import matplotlib.pyplot as plt
import numpy as np
x=np.random.uniform(0.0,5,250)
plt.hist(x,5)
plt.show()
'''
Histogram Explained
We use the array from the example above to draw a histogram with 5 bars.
The first bar represents how many values in the array are between 0 and 1.
The second bar represents how many values are between 1 and 2.
Etc.
Which gives us this result:
52 values are between 0 and 1
48 values are between 1 and 2
49 values are between 2 and 3
51 values are between 3 and 4
50 values are between 4 and 5
Note: The array values are random numbers and will not show the exact same result on your computer.
Big Data Distributions
An array containing 250 values is not considered very big, but now you know how to create a random set of values, and by changing the parameters, you can create the data set as big as you want.
Example
Create an array with 100000 random numbers, and display them using a histogram with 100 bars:
import numpy
import matplotlib.pyplot as plt
x = numpy.random.uniform(0.0, 5.0, 100000)
plt.hist(x, 100)
plt.show()
'''
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/file2_handling.py
|
<gh_stars>0
f=open("a.txt","w")
f.write(" Oops THIS FILE IS DELETED OR NO LONGER SUPOORTED this is me and you /n,")
f.close()
# now this text has been added in the text file now print it.
f=open("a.txt","r")
print(f.readline())
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut6.py
|
<reponame>JayramMardi/codeMania
# datetime is a buit in module in the python # how to use just use the syntax datetime.datetime.now () or you can create your date by using datetime.datetime(year,month,day, microsecond)
import datetime
x=datetime.datetime(3000,12,3, 20 , 17 ,int(5.999))
# here i use TYPECASTING METHOD by convert float to int value "5"
print(x)
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/tut5_normal_distribution.py
|
'''
Machine Learning - Normal Data Distribution
Normal Data Distribution
In the previous chapter we learned how to create a completely random array, of a given size, and between two given values.
In this chapter we will learn how to create an array where the values are concentrated around a given value.
In probability theory this kind of data distribution is known as the normal data distribution, or the Gaussian data distribution, after the mathematician <NAME> who came up with the formula of this data distributio
'''
import matplotlib.pyplot as plt
import numpy as np
speed=np.random.normal(5.0,1.0,100000)
plt.hist(speed,100)
print(speed)
plt.show()
'''
Note: A normal distribution graph is also known as the bell curve because of it's characteristic shape of a bell.
Histogram Explained
We use the array from the numpy.random.normal() method, with 100000 values, to draw a histogram with 100 bars.
We specify that the mean value is 5.0, and the standard deviation is 1.0.
Meaning that the values should be concentrated around 5.0, and rarely further away than 1.0 from the mean.
And as you can see from the histogram, most values are between 4.0 and 6.0, with a top at approximately 5.0.
'''
'''
Machine Learning - Scatter Plot
Scatter Plot
A scatter plot is a diagram where each value in the data set is represented by a dot.
The Matplotlib module has a method for drawing scatter plots, it needs two arrays of the same length, one for the values of the x-axis, and one for the values of the y-axis:
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
The x array represents the age of each car.
The y array represents the speed of each car.
'''
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut13_Bars.py
|
<filename>codeMania-python-matplotlib/tut13_Bars.py
# chapter bars ploting [matplotlib]
'''
from numpy.lib.polynomial import polyfit
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
'''
import matplotlib.pyplot as plt
import numpy as r
x=r.array(["A","D","F","G","H","J","K","L"])
y=r.array([2,3,4,5,6,7,8,9])
plt.bar(x,y)
plt.show()
# The bar() function takes arguments that describes the layout of the bars.
# The categories and their values represented by the first and second argument as arrays.
u=(["apple","banana"])
p=([450,900])
plt.title("GROCERY CHART",c="red")
plt.bar(u,p)
plt.show()
m=(["A","D","F","G"])
# Horizontal Bars
#If you want the bars to be displayed horizontally instead of vertically, use the barh() function:
m=(["apple","banana","grapes","mangoes"])
n=([2,3,4,5])
plt.barh(m,n)
plt.show()
#Bar Color
# The bar() and barh() takes the keyword argument color to set the color of the bars:
o=(["apple","banana"])
p=([1,900])
plt.barh(o,p,color="#7a69cf")
plt.show()
# Color Names
# You can use any of the 140 supported color names.
'''
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
'''
o=(["apple","banana","citrus fruit","mangoes"])
p=([779,900,455,766])
plt.bar(o,p,width=0.1)
plt.show()
#The default width value is 0.8
'''
The default width value is 0.8
Note: For horizontal bars, use height instead of width.
'''
# Bar Height
# The barh() takes the keyword argument height to set the height of the bars:
q=(["apple", "banana","watermelon","mangoes"])
w=([3, 8, 1, 10])
plt.barh(q,w, height=0.8 )
plt.show()
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut7matplotlib.py
|
# Chapter matplotlib pyplot
'''
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example
Draw a line in a diagram from position (0,0) to position (6,250):
'''
import sys
import matplotlib
# matplotlib.use('agg') Don't use this line because this makes code un run
import matplotlib.pyplot as plt
import numpy as r
xpoint=r.array([0,6])
ypint=r.array([0,340])
plt.plot(xpoint,ypint)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
|
JayramMardi/codeMania
|
codeMania-python-begginer/11.py
|
import hashlib
crypto_=hashlib.md5()
crypto_.update(b"hello world")
print(crypto_.hexdigest())
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/file_handling.py
|
<reponame>JayramMardi/codeMania
f=open("ooops.txt","w")
f.write("this is me text5 article and write the machine function language in teh write the code into the andrioid studio.")
f.close()
print(f.read())
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/ossmos.py
|
<gh_stars>0
import os
f=os.remove("ooops.txt")
# p=os.remove("a.txt")
s=os.remove("demo.txt")
|
JayramMardi/codeMania
|
codeMania-python-AI-Machine-learning/tut2_standard_deviation.py
|
<reponame>JayramMardi/codeMania
'''
What is Standard Deviation?
Standard deviation is a number that describes how spread out the values are.
A low standard deviation means that most of the numbers are close to the mean (average) value.
A high standard deviation means that the values are spread out over a wider range.
Example: This time we have registered the speed of 7 cars:
speed = [86,87,88,86,87,85,86]
The standard deviation is:
0.9
Meaning that most of the values are within the range of 0.9 from the mean value, which is 86.4.
Let us do the same with a selection of numbers with a wider range:
speed = [32,111,138,28,59,77,97]
The standard deviation is:
37.85
Meaning that most of the values are within the range of 37.85 from the mean value, which is 77.4.
As you can see, a higher standard deviation indicates that the values are spread out over a wider range.
The NumPy module has a method to calculate the standard deviation:
Example
Use the NumPy std() method to find the standard deviation:
'''
import numpy as r
speed=[86,87,88,86,87,85,86]
o=r.std(speed)
print(o)
'''
Variance
Variance is another number that indicates how spread out the values are.
In fact, if you take the square root of the variance, you get the standard deviation!
Or the other way around, if you multiply the standard deviation by itself, you get the variance!
To calculate the variance you have to do as follows:
1. Find the mean:
(32+111+138+28+59+77+97) / 7 = 77.4
2. For each value: find the difference from the mean:
32 - 77.4 = -45.4
111 - 77.4 = 33.6
138 - 77.4 = 60.6
28 - 77.4 = -49.4
59 - 77.4 = -18.4
77 - 77.4 = - 0.4
97 - 77.4 = 19.6
3. For each difference: find the square value:
(-45.4)2 = 2061.16
(33.6)2 = 1128.96
(60.6)2 = 3672.36
(-49.4)2 = 2440.36
(-18.4)2 = 338.56
(- 0.4)2 = 0.16
(19.6)2 = 384.16
4. The variance is the average number of these squared differences:
(2061.16+1128.96+3672.36+2440.36+338.56+0.16+384.16) / 7 = 1432.2
Luckily, NumPy has a method to calculate the variance:
Example
Use the NumPy var() method to find the variance:
'''
import numpy as r
speed=[32,111,138,28,59,77,97]
p=r.var(speed)
print(p)
'''Standard Deviation
As we have learned, the formula to find the standard deviation is the square root of the variance:
√1432.25 = 37.85
Or, as in the example from before, use the NumPy to calculate the standard deviation:
Example
Use the NumPy std() method to find the standard deviation:
import numpy
'''
speed = [32,111,138,28,59,77,97]
x = r.std(speed)
print(x)
|
JayramMardi/codeMania
|
codeMania-python-matplotlib/tut10.py
|
import matplotlib.pyplot as plt
import numpy as np
x=np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y=np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
font1={'family':'serif','color':'black','size':'20'}
font2={'family':'serif','color':"red","size":'29'}
plt.plot(x,y)
plt.title("MAGA Point",fontdict=font1,loc='right')
plt.xlabel("azure network",fontdict=font2)
plt.ylabel("project insight",fontdict=font2)
plt.grid(color='red',linestyle='-',lw= 2)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.