LoginSignup
101
138

More than 3 years have passed since last update.

【まとめ】Pythonを高高速速で復習する

Last updated at Posted at 2019-05-05

はじめに

日本語の説明より、問題⇨答えの形式が記憶掘り起こしに最速だと考え、作成に至りました。

関数もオブジェクト


def fun() : print("a")
fun2 = fun ; fun2()
a

クロージャ(関数閉包)


def fun (a) :
    #関数の実態
    def fun2 (b) :
        return a*b
    return fun2

a2 = fun(100) #aへの代入
b2 = a2(200) #bへの代入
print(b2)
20000

無名関数lambda


aiueo = (lambda a,b : a*b)(100,200)
print(aiueo)
20000

print関数

a = 100; b = 200; c = 300
print(a, b, c, sep=",", end="end\n")

100,200,300end

文字列のスライス


a = "0123456789"
print(a[:])
print(a[2::])
print(a[2:7:])
print(a[2:7:2]) #2文字おきにステップ
print(a[::-1]) #最後尾の位置は-1
print(a[-1:-6:-2]) #逆向きに2文字ステップ
0123456789
23456789
23456
246
9876543210
975

変数名の付け方

  • ✖︎a,b(汎用的) ◯何を示すかわかる名前
  • ✖︎myName(キャメルケース) ◯my_name(スネークケース)
  • 1文字目には数字使用不可

文字列のインスタンスメソッド


a = "may the God bee with you._________"
b = a.title() ; print(b) #映画のタイトルみたいに
c = b.replace("God","Force",1) ; print(c) #1個だけ置換
d = c.rstrip("_") ; print(d) #指定された不要文字削除

May The God Bee With You._________
May The Force Bee With You._________
May The Force Bee With You.

文字列のインスタンスメソッド2「埋め込み」


name = "hanako"; age = "45"
a = "{}は{}歳"
print(a.format(name,age)) #変数埋め込み

b = "{1}は{0}歳で超絶可愛い"
print(b.format("20","まいんちゃん"))

print(f"{name}{age}歳")

hanakoは45歳
まいんちゃんは20歳で超絶可愛い
hanakoは45歳

共有渡し(≒参照渡し)

Pythonのイコールの意味は2つ

  • 変数の代入(共有渡し。アドレスを代入)
  • 新規作成(オブジェクトを新規作成して、そのアドレスを代入)

リストの中身変更は、アドレスは変わらない。


list1 = [1, 2, 3] #[1,2,3]のアドレスを新しく作って、list1に代入
list2 = list1 #2が持つアドレスを1と共有
list1[0] = 10
print(list2)
print(list1 is list2) #参照先が同じか
print(list1 == list2) #参照先の中身が同じか

[10, 2, 3]
True
True

リストの場合はmutableな為、参照先の中身を書き換えられる。

immutableな文字列や数字の変更は、アドレス変更せざるをえない。

a = 1
b = a
a = 2 #2のアドレスを新しく作って、aに代入
print(b)
print(a is b)
print(a == b)

1
False
False

数値や文字列の場合はimmutableな為、中身だけ変更できない。参照先を変更し、参照先の中身を新規作成

データ型の種類

  • リスト(インデックスで管理,型混在OK)
  • 辞書(キーで管理)
  • タプル(複数の型をまとめたい)
  • セット(集合演算したい)
  • 配列(多次元で扱いたい)

リスト


>>> list(range(0,10)) #組み込み関数list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [[0, 1], [2, 3], [4, 5]]
>>> a[2][0] #大きく動いてから、小さく探すと覚える
4

折れ線グラフの書き方

import matplotlib.pyplot as aiueo
x = [1,2,3,4,5,6,7,8,9]
y = [1,9,2,8,3,7,4,6,5]
aiueo.plot(x,y,marker="o") #マーカー付き
aiueo.title("aiueo")
aiueo.xlabel("x")
aiueo.ylabel("y")
aiueo.grid(True) #グリッドを付ける
aiueo.show()

結果

スクリーンショット 2019-05-03 20.56.24.png

散布図の書き方

import matplotlib.pyplot as aiueo
x = [1,2,3,4,5,6,7,8,9]
y = [1,9,2,8,3,7,4,6,5]
aiueo.scatter(x,y)
aiueo.show()

結果

円グラフの書き方

import matplotlib.pyplot as aiueo
labels = ["A","B","C","D"]
x = [10,20,30,40]
ex = [0,0,0,0.1]
aiueo.pie(x, explode=ex, labels = labels, autopct = '%1.1f%%', startangle = 90)
#autopctってよくわかってない
aiueo.show()

結果



配列を作り方

Numpyライブラリを使う。多次元配列の扱いに優れている。
要素の型を指定できる。

import numpy as np
aiueo = np.array([1, 2, 3, 4, 5, 6], dtype=float)
print(aiueo)
hoge = aiueo.reshape(2, 3)
print(hoge)

結果

[1. 2. 3. 4. 5. 6.]
[[1. 2. 3.]
 [4. 5. 6.]]

配列の標準偏差

import numpy as np
sigma = 3.5 #分散
mu = 65 #平均
#点数のサンプルデータ(正規分布の乱数で作成する)
data = sigma * np.random.randn(200) + mu
x = float(input("得点は?:"))
t_score = 10*(x - data.mean())/data.std() + 50 #偏差値
print("平均点:", round(data.mean(),1))
print("標準偏差:", round(data.std(),1))
print("偏差値:", round(t_score, 1))

結果

得点は?:60
平均点: 64.8
標準偏差: 3.4
偏差値: 36.0

教師あり学習

学習データ = 訓練データ + テストデータ
訓練データ ⇄ 教師データ
テストデータ ⇄ 教師データ

機械学習は、まずデータセット

#sklearnパッケージからdatasetsモジュールをimport
from sklearn import datasets
digits = datasets.load_digits()

#手書き文字のデータセットdigitsには5種類のデータがある
print(dir(digits))

print(digits.data.shape) #画像データ
print(digits.images.shape) #画像データ8*8
print(digits.target.shape) #画像データに対応する数字
print(digits.target_names.shape) #書いた数字の種類

print(digits.data) #1797*64の二次元配列
print(digits.images) #1797*8*8の三次元配列
print(digits.target) #要素1797の一次元配列
print(digits.target_names) #要素10の一次元配列

print(digits.data[0]) #なんか一個取り出してみる
print(digits.images[0])
print(digits.target[0])

結果

(1797, 64)
(1797, 8, 8)
(1797,)
(10,)
[ 0.  0.  5. 13.  9.  1.  0.  0.  0.  0. 13. 15. 10. 15.  5.  0.  0.  3.
 15.  2.  0. 11.  8.  0.  0.  4. 12.  0.  0.  8.  8.  0.  0.  5.  8.  0.
  0.  9.  8.  0.  0.  4. 11.  0.  1. 12.  7.  0.  0.  2. 14.  5. 10. 12.
  0.  0.  0.  0.  6. 13. 10.  0.  0.  0.]
[[ 0.  0.  5. 13.  9.  1.  0.  0.]
 [ 0.  0. 13. 15. 10. 15.  5.  0.]
 [ 0.  3. 15.  2.  0. 11.  8.  0.]
 [ 0.  4. 12.  0.  0.  8.  8.  0.]
 [ 0.  5.  8.  0.  0.  9.  8.  0.]
 [ 0.  4. 11.  0.  1. 12.  7.  0.]
 [ 0.  2. 14.  5. 10. 12.  0.  0.]
 [ 0.  0.  6. 13. 10.  0.  0.  0.]]
0

学習器にかける

from sklearn import datasets
from sklearn import svm

digits = datasets.load_digits()

n_train = len(digits.data)*2//3
X_train = digits.data[:n_train]
y_train = digits.target[:n_train]
X_test = digits.data[n_train:]
y_test = digits.target[n_train:]

clf = svm.SVC(gamma=0.001)
clf.fit(X_train, y_train)

print(clf.score(X_test, y_test))

結果

0.9632721202003339
101
138
20

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
101
138