101 - 151 Flashcards

1
Q

os.path.isdir(path)

A

возвращает True если путь path существует и является каталогом, False в противном случае.

os.path.isdir('/home/User/Documents/file.txt')
os.path.isdir('/home/User/Documents')
👉 True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

os.path.islink(path)

A

возвращает True если путь path относится к существующей записи каталога, который является символической ссылкой.

p = pathlib.Path('file.txt')
p.touch()
os.symlink(p, 'link')

os.path.islink('link')
👉 True

os.path.islink('file.txt')
👉 False

p.unlink()
os.unlink('link')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)

A

создает жесткую ссылку, указывающую на src с именем dst.

  • src - str, путь в файловой системе на который указывает ссылка
  • dst - имя ссылки (str путь в файловой системе)
  • src_dir_fd=None - int дескрипторов каталогов на который указывает ссылка
  • dst_dir_fd=None - int имя ссылки, дескрипторов каталогов
  • follow_symlinks=True - bool, переходить ли по ссылкам
scr = 'tt.py'
dst = 'link_tt.py'
os.link(scr, dst)
os.path.isfile(dst)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

os.symlink()

A

создает символическую ссылку, указывающую на src с именем dst.

  • src - str, путь в файловой системе на который указывает ссылка,
  • dst - имя ссылки (str путь в файловой системе),
  • target_is_directory=False - bool, в Windows ссылка как каталог.
  • dir_fd=None - int, дескрипторов каталогов.
src = '/home/ihritik/file.txt'
dst = '/home/ihritik/Desktop/file(symlink).txt'

os.symlink(src, dst)
src = '/usr/bin/python'
dst = '/tmp/python'

os.symlink(src, dst)
os.readlink(dst)
👉  '/usr/bin/python'

os.path.islink(dst)
👉 True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

os.readlink(path, *, dir_fd=None)

A

вернет путь, на который указывает символическая ссылка. Результатом может быть абсолютный или относительный путь.

  • path - str или bytes, символическая ссылка,
  • dir_fd=None - int, дескриптор каталога.
src = '/usr/bin/python'
dst = '/tmp/python'
os.symlink(src, dst)
os.readlink(dst)

👉 '/usr/bin/python'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

os.path.relpath()

A

возвращает относительный путь к файлу path либо из текущего каталога, либо из необязательного начального каталога start.

path = "/home/User/Desktop/file.txt"
start = "/home/User/"
os.path.relpath(path, start)

👉 Desktop/file.txt
path = "/home/User/Desktop/file.txt"
start = "/home/docs-python/Docs"
os.path.relpath(path, start)

👉 '../../User/Desktop/file.txt'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

os.path.isabs(path)

A

возвращает True если путь является абсолютным, False в противном случае.

os.path.isabs('/home/User/Documents')
os.path.isabs('home/User/Documents')
👉 False
os.path.isabs('../User/Documents')
👉 False
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

os.path.samefile(path1, path2)

A

возвращает True, если оба аргумента пути path1 и path2 ссылаются на один и тот же файл или каталог. Аргументы path1 и path2 должны быть одинакового типа и могут принимать байтовые или текстовые строки.

path = '/home/docs-python/Desktop/file.txt'
link = '/home/docs-python/link.txt'
os.path.samefile(path, link)

👉 True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

os.path.splitext(path)

A

делит путь path на двойной кортеж (root, ext), так что root + ext == path. Элемент кортежа ext будет пустой если path начинается с точки и содержит не более одной точки. Ведущие точки на базовом имени игнорируются.

os.path.splitext('/home/User/Desktop/file.txt')
👉 ('/home/User/Desktop/file', '.txt')
os.path.splitext('/home/User/Desktop/')
👉 ('/home/User/Desktop/', '')
os.path.splitext('/home/User/Desktop')
👉 ('/home/User/Desktop', '')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

sys.exit([arg])

A

considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.

age = 17
if age < 18:
    # exits the program
    sys.exit("Age less than 18")    
else:
    print("Age is not less than 18")

👉 An exception has occurred, use %tb to see the full traceback. SystemExit: Age less than 18
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

pandas.DataFrame.nunique(axis=0, dropna=True)

A

Count the number of distinct elements in the specified axis. Return Series with the number of distinct elements. Can ignore NaN values.

df = pd.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
df.nunique()

A    3
B    
df = pd.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
df.nunique(axis=1)
0    1
1    2
2    2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

pandas.DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors=’ignore’)

A

the method allows you to change the row indexes and the column labels.

data = {"age": [50, 40, 30], "qualified": [True, False, False]}
idx = ["Sally", "Mary", "John"]
df = pd.DataFrame(data, index=idx)

newdf = df.rename({"Sally": "Pete", "Mary": "Patrick", "John": "Paula"})
print(newdf)

             age  qualified
Pete       50       True
Patrick   40      False
Paula     30      False
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df.rename(columns={"A": "a", "B": "c"})
   a  c
0  1  4
1  2  5
2  3  6
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

pandas.DataFrame.resample(rule, axis=0, closed=None, label=None, convention=’start’, kind=None, loffset=None, base=None, on=None, level=None, origin=’start_day’, offset=None)

A

Resample time-series data. Convenience method for frequency conversion and resampling of time series.

index = pd.date_range('1/1/2000', periods=9, freq='T')
series = pd.Series(range(9), index=index)
series
2000-01-01 00:00:00    0
2000-01-01 00:01:00    1
2000-01-01 00:02:00    2
2000-01-01 00:03:00    3
2000-01-01 00:04:00    4
2000-01-01 00:05:00    5
2000-01-01 00:06:00    6
2000-01-01 00:07:00    7
2000-01-01 00:08:00    8

Downsample the series into 3-minute bins and sum the values of the timestamps falling into a bin.

series.resample('3T').sum()
2000-01-01 00:00:00     3
2000-01-01 00:03:00    12
2000-01-01 00:06:00    21
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=NoDefault.no_default, inclusive=None, **kwargs)

A

Return a fixed frequency DatetimeIndex. Returns the range of equally spaced time points such that they all satisfy start <[=] x <[=] end.

pd.date_range(start='1/1/2018', end='1/08/2018')
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
                         '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],
                          dtype='datetime64[ns]', freq='D')
pd.date_range(end='1/1/2018', periods=8)
DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',
                         '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],
                          dtype='datetime64[ns]', freq='D')
pd.date_range(start='1/1/2018', periods=5, freq='M')
DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', 
                         '2018-04-30','2018-05-31'],
                          dtype='datetime64[ns]', freq='M')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

pandas.DataFrame.applymap(func, na_action=None, **kwargs)

A

Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame.

df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])
df.applymap(lambda x: x**2)

           0          1
0   1.000000   4.494400
1  11.262736  20.857489
df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])
df.applymap(lambda x: len(str(x)))

   0  1
0  3  4
1  5  5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

numpy.tile(A, reps)

A

Construct an array by repeating A the number of times given by reps. If reps have length d, the result will have a dimension of max(d, A.ndim).

a = np.array([0, 1, 2])
np.tile(a, 2)
👉  array([0, 1, 2, 0, 1, 2])
a = np.array([0, 1, 2])
np.tile(a, (2, 2))
👉  array([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]])
a = np.array([0, 1, 2])
np.tile(a, (2, 1, 2))
👉  array([[[0, 1, 2, 0, 1, 2]], [[0, 1, 2, 0, 1, 2]]])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

numpy.triu(m, k=0)

A

The upper triangle of an array. Return a copy of an array with the elements below the k-th diagonal zeroed. For arrays with ndim exceeding 2, triu will apply to the final two axes.

np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)

array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 0,  8,  9],
           [ 0,  0, 12]])
np.triu(np.arange(3*4*5).reshape(3, 4, 5))

array([[[ 0,  1,  2,  3,  4],
           [ 0,  6,  7,  8,  9],
           [ 0,  0, 12, 13, 14],
           [ 0,  0,  0, 18, 19]],
          [[20, 21, 22, 23, 24],
           [ 0, 26, 27, 28, 29],
           [ 0,  0, 32, 33, 34],
           [ 0,  0,  0, 38, 39]],
          [[40, 41, 42, 43, 44],
           [ 0, 46, 47, 48, 49],
           [ 0,  0, 52, 53, 54],
           [ 0,  0,  0, 58, 59]]])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

numpy.linalg.matrix_rank(A, tol=None, hermitian=False)

A

Return the matrix rank of an array using the SVD method. The rank of the array is the number of singular values of the array that are greater than tol.

from numpy.linalg import matrix_rank
matrix_rank(np.eye(4)) # Full rank matrix
👉 4
I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
matrix_rank(I)
👉 3
matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
👉 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

pandas.DataFrame.drop_duplicates(subset=None, keep=’first’, inplace=False, ignore_index=False)

A

Return DataFrame with duplicate rows removed. Considering certain columns is optional. Indexes, including time indexes, are ignored.

By default, it removes duplicate rows based on all columns.
df.drop_duplicates()
To remove duplicates on specific column(s), use a subset.
df.drop_duplicates(subset=['brand'])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

pandas.Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)

A

Return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.

index = pd.Index([3, 1, 2, 3, 4, np.nan])
index.value_counts()
3.0    2
1.0    1
2.0    1
4.0    1
dtype: int64
s = pd.Series([3, 1, 2, 3, 4, np.nan])
s.value_counts(normalize=True)
3.0    0.4
1.0    0.2
2.0    0.2
4.0    0.2
dtype: float64
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

pandas.DataFrame.merge(right, how=’inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=(‘_x’, ‘_y’), copy=True, indicator=False, validate=None)

A

updates the content of two DataFrame by merging them together, using the specified method(s). Use the parameters to control which values to keep and which to replace.

You can use .merge() when you want to merge based on a given column and .join() when you want to join on the index.

orders_df = Olist().get_data()["orders"]
reviews_df = Olist().get_data()["order_reviews"]

together = pd.merge(left=orders_df, right=reviews_df, how="left", on="order_id")
together[together["review_id"].isnull() == True]["order_id"].count()
left_merged_df = a_df.merge(b_df, on="Country", how="left")
22
Q

scipy.stats.hypsecant.cdf(x, beta)

A

get the value of the cumulative distribution function.

from scipy.stats import hypsecant
beta = 1
gfg = hypsecant.cdf(0.3, beta)

👉 0.29342577051097424
from scipy.stats import hypsecant
beta = 4
gfg = hypsecant.cdf(0.9, beta)

👉 0.028659835738036286
23
Q

Univariate Linear Regression

A

type of data in which the result depends only on one variable. For instance, a dataset of points on a line can be considered as univariate data where abscissa can be considered as an input feature and ordinate can be considered as

24
Q

unittest

A

the first level of software testing where the smallest testable parts of the software are tested.

import unittest

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self. assertTrue('FOO'.isupper())
        self. assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        #check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if \_\_name\_\_ == '\_\_main\_\_':
    unittest.main()

test_isupper (\_\_main\_\_.TestStringMethods) ... ok
test_split (\_\_main\_\_.TestStringMethods) ... ok
test_upper (\_\_main\_\_.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
25
Q

statistics.quantiles(data, *, n=4, method=’exclusive’)

A

Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals.

data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
        100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
        106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
        111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
        103, 107, 101, 81, 109, 104]
[round(q, 1) for q in quantiles(data, n=10)]

👉 [81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]
26
Q

statistics.stdev()

A

calculates standard deviation from a sample of data, rather than an entire population.

import statistics

sample = [1, 2, 3, 4, 5]
print(statistics.stdev(sample))

👉 1.5811388300841898
27
Q

doctest

python -m doctest -v file.py

A

finds patterns in the docstring that looks like interactive shell commands. The input and expected output are included in the docstring, then the doctest module uses this docstring for testing the processed output.

# Добавить файл который протестирует все файлы модуля | можно добавить докстринг прямо в чистый
файл с импортом как докстринге и тем что нужно протестировать 
("""from test.py import * fun(2,2) >>>4)"""

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests
from doctest import testmod

def factorial(n):
    '''
    >>> factorial(3)
    6
    >>> factorial(5)
    120
    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    '''

    if n <= 1:
        return 1
    return n * factorial(n - 1)
  
# call the testmod function
if \_\_name\_\_ == '\_\_main\_\_':
    testmod(name ='factorial', verbose = True)

👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
Trying:
    factorial(3)
Expecting:
    6
ok
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
1 items had no tests:
    factorial
1 items passed all tests:
   3 tests in factorial.factorial
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
28
Q

statistics.variance()

A

helps to calculate the variance from a sample of data.

import statistics

sample = [2.74, 1.23, 2.63, 2.22, 3, 1.98]

print("Variance of sample set is % s"
      %(statistics.variance(sample)))

👉 Variance of sample set is 0.40924
29
Q

pip install -r requirements.txt

A

позволяет установить все пакеты находящиеся в текстовом файле.

30
Q

pyenv shell

A

менеджер версий python. Позволяет легко переключаться между версиями python любого уровня, вплоть до 3 знака, например 3.8.5 рядом с 3.9.10.

pyenv install 3.10.2
pyenv shell 
pyenv install --list
pyenv install 3.7.10
pyenv versions
31
Q

datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

A

представляет собой (локальное) время, независимое от какого-либо конкретного дня и подлежащее настройке с помощью объекта datetime.tzinfo().

import datetime

time = datetime.time(22, 45, 15)
print(time.hour, time.minute, time.second, time.microsecond)

👉 22 45 15 0
32
Q

datetime.date(year, month, day)

A

объект даты, который представляет дату - год, месяц и день в идеализированном календаре.

👉 year - год в пределах MINYEAR <= year <= MAXYEAR,
👉 month - месяц в пределах 1 <= month <= 12,
👉 day - день в пределах 1 <= day <= n, n - количество дней в данном месяце и году.

import datetime
date = datetime.date(2020, 7, 14)
print(date)

date.day
👉 14

date.month
👉 7

date.year
👉 2020
33
Q

string.splitlines()

A

used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional).

txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x)

👉 ['Thank you for the music', 'Welcome to the jungle']
Split the string, but keep the line breaks:

txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines(True)
print(x)

👉 ['Thank you for the music\n', 'Welcome to the jungle']
34
Q

enum.Enum and enum.auto

A

перечисление, что полностью отражает суть модуля.
создать автоматические значения для ваших перечислений.

import enum
class PigeonState(enum.Enum):
    eating = 0
    sleeping = 1
    flying = 2

PigeonState.sleeping.value
👉 1
class Num(Enum):
    one = 1
    two = 2
    three = 3
for n in Num:
    print(n)

👉 Num.one
👉 Num.two
👉 Num.three
from enum import auto, Enum
class Shapes(Enum):
    CIRCLE = auto()
    SQUARE = auto()
    OVAL = auto()

👉 Shapes.CIRCLE
35
Q

max(iterable, key)

A

the function returns the item with the highest value or the item with the highest value in an iterable. If the values are strings, an alphabetical comparison is done.

a_list = ["aaa", "bb", "cc", "d"]
print(max(a_list, key=len))

👉 aaa
x = max(5, 10)
print(x)

👉 10
36
Q

functools.total_ordering()

A

comparison methods that help in comparing classes without explicitly defining a function for it.

from functools import total_ordering

@total_ordering
class num:
    def \_\_init\_\_(self, value):
        self.value = value

    def \_\_lt\_\_(self, other):
        return self.value < other.value

    def \_\_eq\_\_(self, other):
        return self.value != other.value

print(num(2) < num(3))   # True
print(num(2) > num(3))   # False
print(num(3) == num(3))  # False
print(num(3) == num(5))  # True
37
Q

glob

A

used to define techniques to match specified patterns. Used to retrieve files/pathnames matching a specified pattern.

import glob

print('Named explicitly:')
for name in glob.glob('/home/geeks/Desktop/gfg/data.txt'):
    print(name)
print('\nNamed with wildcard *:')
for name in glob.glob('/home/geeks/Desktop/gfg/*'):
    print(name)
38
Q

subprocess

A

the module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

subprocess.run("exit 1", shell=True, check=True)
39
Q

queue.Queue()

A

useful in threaded programming when information must be exchanged safely between multiple threads.

import queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

threading.Thread(target=worker, daemon=True).start()

Send thirty task requests to the worker.
for item in range(30):
    q.put(item)

Block until all tasks are done.
q.join()
40
Q

reduce(function, iterable[, initializer])

A

модуля functools кумулятивно применяет функцию к элементам итерируемой iterable последовательности, сводя её к единственному значению.

  • function - пользовательская функция, принимающая 2 аргумента,
  • iterable - итерируемая последовательность,
  • initializer - начальное значение.
from functools import reduce
my_list = [2, 5, 8, 10, 9, 3]
e = reduce(lambda x , y : x + y, my_list)

print(e)
👉 37
reduce(lambda x, y : x + y, [1,2,3], -3)
👉 3
items = [10, 20, 30, 40, 50]
sum_all = reduce(lambda x,y: x + y, items)

print(sum_all)
👉 150
items = [1, 24, 17, 14, 9, 32, 2]
all_max = reduce(lambda a,b: a if (a > b) else b, items)

print(all_max)
👉 32
41
Q

tabulate

A

display table

позволяет создавать красивые текстовые таблички.

pip install tabulate
from tabulate import tabulate

mydata = [
    ["Nikhil", "Delhi"],
    ["Ravi", "Kanpur"],
    ["Manish", "Ahmedabad"],
    ["Prince", "Bangalore"]
]
head = ["Name", "City"]
print(tabulate(mydata, headers=head, tablefmt="grid"))

mydata = [
    ['a', 'b', 'c'],
    [12, 34, 56],
    ['Geeks', 'for', 'geeks!']
]
# display table
print(tabulate(mydata))
42
Q

string.digits

A

will give the lowercase letters ‘0123456789’.

import string 

result = string.digits 
print(result)

👉 0123456789
43
Q

string.ascii_letters

A

basically concatenation of ascii_lowercase and ascii_uppercase string constants.

import string

result = string.ascii_letters
print(result)

👉 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
44
Q

string.ascii_uppercase

A

will give the uppercase letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.

import string

result = string.ascii_uppercase
print(result)

👉 ABCDEFGHIJKLMNOPQRSTUVWXYZ
45
Q

string.ascii_lowercase

A

will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’.

import string

result = string.ascii_lowercase
print(result)

👉 abcdefghijklmnopqrstuvwxyz
46
Q

pycallgraph2

A

Python Call Graph is a Python module that creates call graph visualizations for Python applications.

pip install pycallgraph2
from pycallgraph2 import PyCallGraph
from pycallgraph2.output import GraphvizOutput

with PyCallGraph(output=GraphvizOutput()):
    code_to_profile()]
47
Q

pyttsx3

A

text-to-speech conversion library in Python. Unlike alternative libraries, it works offline.

pip install pyttsx3

import pyttsx3
engine = pyttsx3.init()
engine.say(“I will speak this text”)
engine.runAndWait()
48
Q

L2 regularization

A

takes the square of the weights, so the cost of outliers present in the data increases exponentially.

49
Q

L1 regularization

A

takes the absolute values of the weights, so the cost only increases linearly.

50
Q

numpy.loadtxt(fname, dtype=, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=’bytes’, max_rows=None, *, quotechar=None, like=None)

A

Load data from a text file. Each row in the text file must have the same number of values.

c = StringIO("0 1\n2 3")
np.loadtxt(c)
array([[0., 1.],
       [2., 3.]])
c = StringIO("1,0,2\n3,0,4")
x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)

x
👉 array([1., 3.])
y
👉 array([2., 4.])
51
Q

numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’’, footer=’’, comments=’# ‘, encoding=None)

A

Save an array to a text file.

x = y = z = np.arange(0.0,5.0,1.0)
np.savetxt('test.out', x, delimiter=',')   # X is an array
np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation