Библиотека Python разработчика | Книги по питону
19.5K subscribers
1.05K photos
391 videos
82 files
988 links
Полезные материалы для питониста по Фреймворкам Django, Flask, FastAPI, Pyramid, Tornado и др.

По всем вопросам @evgenycarter

РКН clck.ru/3Ko7Hq
Download Telegram
Open source инструмент на Python для выбора признаков нейронной сети

Поиск и выбор наиболее полезных признаков в датасете — одна из наиболее важных частей машинного обучения. Ненужные признаки уменьшают скорость обучения, ухудшают возможности интерпретации результатов и, что самое важное, уменьшают производительность работы.

В этой статье мы рассмотрим работу FeatureSelector. Он позволяет нам быстро внедрять эти методы, обеспечивая более эффективный рабочий процесс. Feature Selector — это незавершенный проект, который будет продолжать улучшаться в зависимости от потребностей сообщества.
🔥3
Шаблоны и практика глубокого обучения
Ферлитш Эндрю (2022)

Откройте для себя шаблоны конструирования и воспроизводимые архитектуры, которые направят ваши проекты глубокого обучения от стадии разработки к реализации. В книге рассматриваются актуальные примеры создания приложений глубокого обучения с учетом десятилетнего опыта работы автора в этой области. Вы сэкономите часы проб и ошибок, воспользовавшись представленными здесь шаблонами и приемами. Проверенные методики, образцы исходного кода и блестящий стиль повествования позволят с увлечением освоить даже непростые навыки. По мере чтения вы получите советы по развертыванию, тестированию и техническому сопровождению ваших проектов. Издание предназначено для инженеров машинного обучения, знакомых с Python и глубоким обучением.

Скачать

👉 @python_360
👍10
If you create new objects inside your __init__ it may be better to pass them as arguments and have a factory method instead. It separates business logic from technical details on how objects are created.

In this example __init__ accepts host and port to construct a database connection:

class Query:
def __init__(self, host, port):
self._connection = Connection(host, port)


The possible refactoring is:

class Query:
def __init__(self, connection):
self._connection = connection

@classmethod
def create(cls, host, port):
return cls(Connection(host, port))


This approach has at least these advantages:

• It makes dependency injection easy. You can do Query(FakeConnection()) in your tests.
• The class can have as many factory methods as needed; the connection may be constructed not only by host and port but also by cloning another connection, reading a config file or object, using the default, etc.
• Such factory methods can be turned into asynchronous functions; this is completely impossible for __init__.
👍7👎1
The same string can be represented in different ways in Unicode and the standard is aware of it. It defines two types of equivalence: sequences can be canonically equivalent or compatible.

Canonically equivalent sequences look exactly the same but contain different code points. For example, ö can be just LATIN SMALL LETTER O WITH DIAERESIS (U+00F6) or a combination of o and a diaeresis modifier: LATIN SMALL LETTER O (U+006F) + COMBINING DIAERESIS (U+0308).

Compatible sequences look different but may be treated the same semantically, e. g. ff and ff.

For each of these types of equivalence, you can normalize a Unicode string by compressing or decompressing sequences. In Python, you can use unicodedata for this:

modes = [
# Compress canonically equivalent
'NFC',
# Decompress canonically equivalent
'NFD',
# Compress compatible
'NFKC',
# Decompress compatible
'NFKD',
]
s = '
+ ö'

for mode in modes:
norm = unicodedata.normalize(mode, s)
print('\t'.join([
mode,
norm,
str(len(norm.encode('utf8'))),
]))


NFC + ö 8
NFD
+ ö 9
NFKC ff + ö 7
NFKD ff + ö 8
👍3👎1
Forwarded from Python академия
Что такое аннотации типов?

Аннотации типов – это новая возможность, описанная в PEP484, которая позволяет добавлять подсказки о типах переменных. Они используются, чтобы информировать читателя кода, каким должен быть тип переменной.

Это придаёт немного статический вид коду на динамически типизированном Python. Достигается это синтаксисом: <тип> после инициализации / объявления переменной.

Подписывайтесь на канал 👉@pythonofff
👍7
Usually, you communicate with a generator by asking for data with next(gen). You also can send some values back with g.send(x) in Python 3. But the technique you probably don't use every day, or maybe even isn't aware of, is throwing exceptions inside a generator.

With gen.throw(e) you may raise an exception at the point where the gen generator is paused, i. e. at some yield. If gen catches the exception, get.throw(e) returns the next value yielded (or StopIteration is raised). If gen doesn't catch the exception, it propagates back to you.

In : def gen():
...: try:
...: yield 1
...: except ValueError:
...: yield 2
...:
...: g = gen()
...:

In : next(g)
Out: 1

In : g.throw(ValueError)
Out: 2

In : g.throw(RuntimeError('TEST'))
...
RuntimeError: TEST

You can use it to control generator behavior more precisely, not only by sending data to it but by notifying about some problems with values yielded for example. But this is rarely required, and you have a little chance to encounter g.throw in the wild.

However, the @contextmanager decorator from contextlib does exactly this to let the code inside the context catch exceptions.

In : from contextlib import contextmanager
...:
...: @contextmanager
...: def atomic():
...: print('BEGIN')
...:
...: try:
...: yield
...: except Exception:
...: print('ROLLBACK')
...: else:
...: print('COMMIT')
...:

In : with atomic():
...: print('ERROR')
...: raise RuntimeError()
...:
BEGIN
ERROR
ROLLBACK
👍2👎1
Сверточная нейронная сеть на PyTorch: пошаговое руководство

В данном туториале представлен такой метод — сверточная нейронная сеть (Convolutional Neural Network, CNN), который достигает высоких результатов в задачах классификации картинок. В частности, будет рассмотрена и теория, и практика реализации CNN при помощи PyTorch.

PyTorch — мощный фреймворк глубокого машинного обучения. Его особенность — он чувствует себя как дома в Python, а прототипирование осуществляется очень быстро. Туториал не предполагает больших знаний PyTorch. Весь код для сверточной нейронной сети, рассмотренной здесь, находится в этом репозитории. Давайте приступим.

@BookPython
🔥3
Подборка каналов для IT специалистов 🎯


https://t.me/odin1C_rus Cтатьи, курсы, советы, шаблоны кода 1С
https://t.me/kotlin_lib Подборки полезного материала по Kotlin
https://t.me/nodejs_lib Подборки по Node js и все что с ним связано
https://t.me/React_lib Подборки по React js и все что с ним связано


Программирование C++📌
https://t.me/cpp_lib Библиотека C/C++ разработчика
https://t.me/cpp_knigi Книги для программистов C/C++

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском
https://t.me/python_360 Книги по Python Rus

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика
https://t.me/java_360 Книги по Java Rus

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

Метавселенная, GameFi, Crypto 📌
https://t.me/metaverse360

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий

Excel лайфхак📌
https://t.me/Excel_lifehack
👍3
Как использовать postgresql в приложении django

Django — это гибкий фреймворк для быстрого создания приложений Python. По умолчанию приложения Django хранят данные в легкой базе данных SQLite. Это неплохой вариант при небольших нагрузках или тестировании, однако в среде производства лучше использовать более сложную систему управления базами данных, поскольку она может повысить производительность.

В этом руководстве вы научитесь устанавливать и настраивать СУБД PostgreSQL (Postgres) для хранения данных приложения Django. Мы установим необходимое программное обеспечение, создадим учетные данные БД для нашего приложения, а затем запустим и настроим новый проект Django, который будет использовать этот бэкенд.

#django #postgresql

@BookPython
👍3
The super() function allows referring to the base class. This can be extremely helpful in cases when a derived class wants to add something to the method implementation instead of overriding it completely:

class BaseTestCase(TestCase):
def setUp(self):
self._db = create_db()

class UserTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self._user = create_user()


The function's name doesn't mean excellent or very good. The word super implies above in this context (like in superintendant). Despite what I said earlier, super() doesn't always refer to the base class, it can easily return a sibling. The proper name could be next() since the next class according to MRO is returned.

class Top:
def foo(self):
return 'top'

class Left(Top):
def foo(self):
return super().foo()

class Right(Top):
def foo(self):
return 'right'

class Bottom(Left, Right):
pass

# prints 'right'
print(Bottom().foo())


Mind that super() may produce different results since they depend on the MRO of the original call.

>>> Bottom().foo()
'right'
>>> Left().foo()
'top'
👍5👎2
Как создать чат-бота с нуля на Python: подробная инструкция

В этой статье мы расскажем, как создать своего чат-бота на Python.


Чат-бот — это программа, которая выясняет потребности пользователей, а затем помогает удовлетворить их (денежная транзакция, бронирование отелей, составление документов). Сегодня почти каждая компания имеет чат-бота для взаимодействия с пользователями. Некоторые способы использования чат-ботов:


предоставление информации о рейсе;
предоставление пользователям доступа к информации об их финансах;
служба поддержки.
👍4🔥2
The creation of a class consists of two big steps. First, the class body is evaluated, just like any function body. Second, the resulted namespace (the one that is returned by locals()) is used by a metaclass (type by default) to construct an actual class object.

class Meta(type):
def __new__(meta, name, bases, ns):
print(ns)
return super().__new__(
meta, name,
bases, ns
)


class Foo(metaclass=Meta):
B = 2


The above code prints {'__module__': '__main__', '__qualname__': 'Foo', 'B': 3}.

Obviously, if you do something like B = 2; B = 3, then the metaclass only knows about B = 3, since only that value is in ns. This limitation is based on the fact, that a metaclass works after the body evaluation.

However, you can interfere in the evaluation by providing custom namespace. By default, a simple dictionary is used but you can provide a custom dictionary-like object using the metaclass __prepare__ method.

class CustomNamespace(dict):
def __setitem__(self, key, value):
print(f'{key} -> {value}')
return super().__setitem__(key, value)


class Meta(type):
def __new__(meta, name, bases, ns):
return super().__new__(
meta, name,
bases, ns
)

@classmethod
def __prepare__(metacls, cls, bases):
return CustomNamespace()


class Foo(metaclass=Meta):
B = 2
B = 3


The output is the following:

__module__ -> __main__
__qualname__ -> Foo
B -> 2
B -> 3


And this is how enum.Enum is protected from duplicates.
👍4👎1
The map function calls another function for every element of some iterable. That means that function should accept a single value as an argument:

In : list(map(lambda x: x ** 2, [1, 2, 3]))
Out: [1, 4, 9]


However, if each element of the iterable is tuple, then it would be nice to pass each element of that tuple as a separate argument. It was possible in Python 2, thanks to the tuple parameter unpacking (note the parentheses):

>>> map(lambda (a, b): a + b, [(1, 2), (3, 4)])
[3, 7]


In Python 3, this feature is gone, but there is another solution. itertools.starmap unpacks tuple for you, as though a function is called with a star: f(*arg) (hence the function's name):

In [3]: list(starmap(lambda a, b: a + b, [(1, 2), (3, 4)]))
Out[3]: [3, 7]
👍4👎1
​FaceSwap - это инструмент, который использует глубокое обучение для распознавания и замены лиц на фотографиях и видео. Deepfake)

#GitHub | #Python #Deepfake

👉 @Githublib
👍4
Python provides the powerful library to work with date and time: datetime. The interesting part is, datetime objects have the special interface for timezone support (namely the tzinfo attribute), but this module only has limited support of its interface, leaving the rest of the job to different modules.

The most popular module for this job is pytz. The tricky part is, pytz doesn't fully satisfy tzinfo interface. The pytz documentation states this at one of the first lines: “This library differs from the documented Python API for tzinfo implementations.”

You can't use pytz timezone objects as the tzinfo attribute. If you try, you may get the absolute insane results:

In : paris = pytz.timezone('Europe/Paris')
In : str(datetime(2017, 1, 1, tzinfo=paris))
Out: '2017-01-01 00:00:00+00:09'


Look at that +00:09 offset. The proper use of pytz is following:

In : str(paris.localize(datetime(2017, 1, 1)))
Out: '2017-01-01 00:00:00+01:00'


Also, after any arithmetic operations, you should normalize your datetime object in case of offset changes (on the edge of the DST period for instance).

In : new_time = time + timedelta(days=2)
In : str(new_time)
Out: '2018-03-27 00:00:00+01:00'
In : str(paris.normalize(new_time))
Out: '2018-03-27 01:00:00+02:00'


Since Python 3.6, it's recommended to use dateutil.tz instead of pytz. It's fully compatible with tzinfo, can be passed as an attribute, doesn't require normalize, though works a bit slower.

If you are interested why pytz doesn't support datetime API, or you wish to see more examples, consider reading the decent article on the topic.
👍5👎1
Forwarded from Python академия
Упрощенный вывод данных

Он позволяет вывести строчный массив одной строкой, с разделением запятыми. Нам не нужно использовать .join() и циклы.

Подписывайтесь на канал 👉@pythonofff
👍2
Подборка каналов для IT специалистов 🎯


https://t.me/odin1C_rus Cтатьи, курсы, советы, шаблоны кода 1С
https://t.me/kotlin_lib Подборки полезного материала по Kotlin
https://t.me/nodejs_lib Подборки по Node js и все что с ним связано
https://t.me/React_lib Подборки по React js и все что с ним связано


Программирование C++📌
https://t.me/cpp_lib Библиотека C/C++ разработчика
https://t.me/cpp_knigi Книги для программистов C/C++

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском
https://t.me/python_360 Книги по Python Rus

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика
https://t.me/java_360 Книги по Java Rus

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

Метавселенная, GameFi, Crypto 📌
https://t.me/metaverse360

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий

Excel лайфхак📌
https://t.me/Excel_lifehack
👍1
Python functions can return multiple values:

def edges(lst):
return lst[0], lst[-1]

first, last = edges([1, 2, 3])
assert first == 1
assert last == 3


In truth, lst[0], lst[-1] is a simple tuple. It's returned as usual and then unpacked to first and last:


result = edges([1, 2, 3])
assert isinstance(result, tuple)
first, last = result
assert first == 1
assert last == 3


Usually, you don't care about it at all. However, all these things come to the surface when you use type hints. You have to define the function return value as tuple:

def edges(lst) -> Tuple[int, int]:
return lst[0], lst[-1]


Calling that function is even harder. You may think that you can do something like this:

first: int, last: int = edges([1, 2, 3])

Or at least this:

first, last: Tuple[int, int] = edges([1, 2, 3])

But both ways are incorrect. This is the only reasonable thing you can do to annotate these variables:

first: int
last: int
first, last = edges([1, 2, 3])
👍2👎2
This media is not supported in your browser
VIEW IN TELEGRAM
Обучение с подкреплением на Python с библиотекой Keras

Статья о том, как научить машинку участвовать в гонке с помощью обучения с подкреплением, а персонажей — избегать файерболов. При этом агент способен научиться играть в игру в своем собственном «воображении». В статье — пример обучения с подкреплением (reinforcement learning) на Python с библиотекой Keras.
👍7
This media is not supported in your browser
VIEW IN TELEGRAM
​Pyxel - это игровой движок для Python в стиле ретро.


Благодаря своей простоте, вдохновленной старыми игровыми консолями (например, палитра состоит всего из 16 цветов, и только 4 звука могут быть проиграны одновременно), вы можете легко создавать игры в стиле пиксель-арт.

#GitHub | #Cpp #engine

👉 @Githublib
👍13