input stringlengths 0 929 | output stringlengths 0 10.3k | task stringclasses 3
values | index int64 0 5.38k | liscence stringclasses 4
values | source stringclasses 15
values | instruction stringlengths 13 3.45k |
|---|---|---|---|---|---|---|
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデック... | code_generation | 600 | MIT | nlp_100_knocks | pythonを用いて、今回用いている文章をコーパスと見なし、日本語の述語が取りうる格を調査したい。 動詞を述語、動詞に係っている文節の助詞を格と考え、述語と格をタブ区切り形式で出力せよ。 ただし、出力は以下の仕様を満たすようにせよ。
・動詞を含む文節において、最左の動詞の基本形を述語とする
・述語に係る助詞を格とする
・述語に係る助詞(文節)が複数あるときは、すべての助詞をスペース区切りで辞書順に並べる
「ジョン・マッカーシーはAIに関する最初の会議で人工知能という用語を作り出した。」という例文を考える。 この文は「作り出す」という1つの動詞を含み、「作り出す」に係る文節は「ジョン・マッカーシーは」、「会議で」、「用語を」であると... | |
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデック... | code_generation | 601 | MIT | nlp_100_knocks | pythonを用いて、45のプログラムを改変し、述語と格パターンに続けて項(述語に係っている文節そのもの)をタブ区切り形式で出力せよ。45の仕様に加えて、以下の仕様を満たすようにせよ。
・項は述語に係っている文節の単語列とする(末尾の助詞を取り除く必要はない)
・述語に係る文節が複数あるときは、助詞と同一の基準・順序でスペース区切りで並べる
「ジョン・マッカーシーはAIに関する最初の会議で人工知能という用語を作り出した。」という例文を考える。 この文は「作り出す」という1つの動詞を含み、「作り出す」に係る文節は「ジョン・マッカーシーは」、「会議で」、「用語を」であると解析された場合は、次のような出力になるはずである。
```
作... | |
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデック... | code_generation | 602 | MIT | nlp_100_knocks | pythonを用いて、動詞のヲ格にサ変接続名詞が入っている場合のみに着目したい。46のプログラムを以下の仕様を満たすように改変せよ。
・「サ変接続名詞+を(助詞)」で構成される文節が動詞に係る場合のみを対象とする
・述語は「サ変接続名詞+を+動詞の基本形」とし、文節中に複数の動詞があるときは、最左の動詞を用いる
・述語に係る助詞(文節)が複数あるときは、すべての助詞をスペース区切りで辞書順に並べる
・述語に係る文節が複数ある場合は、すべての項をスペース区切りで並べる(助詞の並び順と揃えよ)
例えば「また、自らの経験を元に学習を行う強化学習という手法もある。」という文から、以下の出力が得られるはずである。
```
学習を行う に ... | |
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデック... | code_generation | 603 | MIT | nlp_100_knocks | pythonを用いて、文中のすべての名詞を含む文節に対し、その文節から構文木の根に至るパスを抽出せよ。 ただし、構文木上のパスは以下の仕様を満たすものとする。
・各文節は(表層形の)形態素列で表現する
・パスの開始文節から終了文節に至るまで、各文節の表現を” -> “で連結する
「ジョン・マッカーシーはAIに関する最初の会議で人工知能という用語を作り出した。」という例文を考える。 CaboChaを係り受け解析に用いた場合、次のような出力が得られると思われる。
```
ジョンマッカーシーは -> 作り出した
AIに関する -> 最初の -> 会議で -> 作り出した
最初の -> 会議で -> 作り出した
会議で -> 作り出し... | |
文中のすべての名詞句のペアを結ぶ最短係り受けパスを抽出せよ.ただし,名詞句ペアの文節番号がi
とj
(i<j
)のとき,係り受けパスは以下の仕様を満たすものとする.
問題48と同様に,パスは開始文節から終了文節に至るまでの各文節の表現(表層形の形態素列)を” -> “で連結して表現する
文節i
とj
に含まれる名詞句はそれぞれ,XとYに置換する
また,係り受けパスの形状は,以下の2通りが考えられる.
文節i
から構文木の根に至る経路上に文節j
が存在する場合: 文節i
から文節j
のパスを表示
上記以外で,文節i
と文節j
から構文木の根に至る経路上で共通の文節k
で交わる場合: 文節i
から文節k
に至る直前のパスと文節j
か... | code_generation | 604 | MIT | nlp_100_knocks | pythonを用いて、文中のすべての名詞句のペアを結ぶ最短係り受けパスを抽出せよ。ただし、名詞句ペアの文節番号がiとj(i<j)のとき、係り受けパスは以下の仕様を満たすものとする。
・パスは開始文節から終了文節に至るまでの各文節の表現(表層形の形態素列)を” -> “で連結して表現する
・文節iとjに含まれる名詞句はそれぞれ、XとYに置換する
また、係り受けパスの形状は、以下の2通りが考えられる。
・文節iから構文木の根に至る経路上に文節jが存在する場合: 文節iから文節jのパスを表示
・上記以外で、文節iと文節jから構文木の根に至る経路上で共通の文節kで交わる場合: 文節iから文節kに至る直前のパスと文節jから文節kに至る直前ま... | |
import pandas as pd
from sklearn.model_selection import train_test_split
newsCorpora = pd.read_table('ch06/NewsAggregatorDataset/newsCorpora.csv', header=None)
newsCorpora.columns = ['ID', 'TITLE', 'URL', 'PUBLISHER', 'CATEGORY', 'STORY', 'HOSTNAME', 'TIMESTAMP']
newsCorpora = newsCorpora[newsCorpora['PUBLISHER'].isi... | code_generation | 605 | MIT | nlp_100_knocks | pythonを用いて、News Aggregator Data Setをダウンロードし、以下の要領で学習データ(train.txt)、検証データ(valid.txt)、評価データ(test.txt)を作成せよ。
1.ダウンロードしたzipファイルを解凍し、readme.txtの説明を読む。
2.情報源(publisher)が”Reuters”, “Huffington Post”, “Businessweek”, “Contactmusic.com”, “Daily Mail”の事例(記事)のみを抽出する。
3.抽出された事例をランダムに並び替える。
4.抽出された事例の80%を学習データ、残りの10%ずつを検証データと評価データ... | |
import joblib
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
X_train = pd.read_table('ch06/train.txt', header=None)
X_valid = pd.read_table('ch06/valid.txt', header=None)
X_test = pd.read_table('ch06/test.txt', header=None)
use_cols = ['TITLE', 'CATEGORY']
X_train.columns = use_cols
X... | code_generation | 606 | MIT | nlp_100_knocks | pythonを用いて、学習データ、検証データ、評価データから特徴量を抽出し、それぞれtrain.feature.txt、valid.feature.txt、test.feature.txtというファイル名で保存せよ。 なお、カテゴリ分類に有用そうな特徴量は各自で自由に設計せよ。記事の見出しを単語列に変換したものが最低限のベースラインとなるであろう。 | |
import pandas as pd
import joblib
from sklearn.linear_model import LogisticRegression
X_train = pd.read_table('ch06/train.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
clf = LogisticRegression(penalty='l2', solver='sag', random_state=0)
clf.fit(X_train, y_train)
joblib.dump(clf... | code_generation | 607 | MIT | nlp_100_knocks | pythonを用いて、学習データを用いて、ロジスティック回帰モデルを学習せよ。 | |
import pandas as pd
from sklearn.linear_model import LogisticRegression
X_train = pd.read_table('ch06/train.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
clf = LogisticRegression(penalty='l2', solver='sag', random_state=0)
clf.fit(X_train, y_train)
y_train = clf.predict(X_train... | code_generation | 608 | MIT | nlp_100_knocks | pythonを用いて、学習データから作成したロジスティック回帰モデルを用い、与えられた記事見出しからカテゴリとその予測確率を計算するプログラムを実装せよ。 | |
import pandas as pd
import joblib
from sklearn.metrics import accuracy_score
X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.txt', header=None)[1]
cl... | code_generation | 609 | MIT | nlp_100_knocks | pythonを用いて、学習データから作成したロジスティック回帰モデルの正解率を、学習データおよび評価データ上で計測せよ。 | |
import pandas as pd
import joblib
from sklearn.metrics import confusion_matrix
X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.txt', header=None)[1]
... | code_generation | 610 | MIT | nlp_100_knocks | pythonを用いて、学習データから作成したロジスティック回帰モデルの混同行列(confusion matrix)を、学習データおよび評価データ上で作成せよ。 | |
import pandas as pd
import joblib
from sklearn.metrics import recall_score, precision_score, f1_score
X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.... | code_generation | 611 | MIT | nlp_100_knocks | pythonを用いて、学習データから作成したロジスティック回帰モデルの適合率、再現率、F1スコアを、評価データ上で計測せよ。カテゴリごとに適合率、再現率、F1スコアを求め、カテゴリごとの性能をマイクロ平均(micro-average)とマクロ平均(macro-average)で統合せよ。 | |
import joblib
clf = joblib.load('ch06/model.joblib')
vocabulary_ = joblib.load('ch06/vocabulary_.joblib')
coefs = clf.coef_
for c in coefs:
d = dict(zip(vocabulary_, c))
d_top = sorted(d.items(), key=lambda x: abs(x[1]), reverse=True)[:10]
print(d_top)
d_bottom = sorted(d.items(), key=lambda x: abs(x... | code_generation | 612 | MIT | nlp_100_knocks | pythonを用いて、学習データから作成したロジスティック回帰モデルの中で、重みの高い特徴量トップ10と、重みの低い特徴量トップ10を確認せよ。 | |
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_valid = pd.read_table('ch06/valid.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt... | code_generation | 613 | MIT | nlp_100_knocks | pythonを用いて、ロジスティック回帰モデルを学習するとき、正則化パラメータを調整することで、学習時の過学習(overfitting)の度合いを制御できる。異なる正則化パラメータでロジスティック回帰モデルを学習し、学習データ、検証データ、および評価データ上の正解率を求めよ。実験の結果は、正則化パラメータを横軸、正解率を縦軸としたグラフにまとめよ。 | |
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_valid = pd.read_table('ch06/valid.feature.txt', header=None)
X_test = pd.read_table('c... | code_generation | 614 | MIT | nlp_100_knocks | pythonを用いて、学習アルゴリズムや学習パラメータを変えながら、カテゴリ分類モデルを学習せよ。検証データ上の正解率が最も高くなる学習アルゴリズム・パラメータを求めよ。また、その学習アルゴリズム・パラメータを用いたときの評価データ上の正解率を求めよ。 | |
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('ch07/GoogleNews-vectors-negative300.bin', binary=True)
us = model['United_States']
print(us) | code_generation | 615 | MIT | nlp_100_knocks | pythonを用いて、Toggle menu
第7章: 単語ベクトル
On this page
60. 単語ベクトルの読み込みと表示
61. 単語の類似度
62. 類似度の高い単語10件
63. 加法構成性によるアナロジー
64. アナロジーデータでの実験
65. アナロジータスクでの正解率
66. WordSimilarity-353での評価
67. k-meansクラスタリング
68. Ward法によるクラスタリング
69. t-SNEによる可視化
単語の意味を実ベクトルで表現する単語ベクトル(単語埋め込み)に関して、以下の処理を行うプログラムを作成せよ。
60. 単語ベクトルの読み込みと表示Permalink
Google... | |
import numpy as np
from gensim.models import KeyedVectors
def cosSim(v1, v2):
return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
model = KeyedVectors.load_word2vec_format('ch07/GoogleNews-vectors-negative300.bin', binary=True)
us1 = model['United_States']
us2 = model['U.S.']
print(cosSim(us1, us2... | code_generation | 616 | MIT | nlp_100_knocks | pythonを用いて、“United States”と”U.S.”のコサイン類似度を計算せよ。 | |
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('ch07/GoogleNews-vectors-negative300.bin', binary=True)
result = model.most_similar(positive=['United_States'])
for i in range(10):
print("{}: {:.4f}".format(*result[i])) | code_generation | 617 | MIT | nlp_100_knocks | pythonを用いて、“United States”とコサイン類似度が高い10語と、その類似度を出力せよ。 | |
import numpy as np
from gensim.models import KeyedVectors
def cosSim(v1, v2):
return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
model = KeyedVectors.load_word2vec_format('ch07/GoogleNews-vectors-negative300.bin', binary=True)
result = model.most_similar(positive=['Spain', 'Athens'], negative=['M... | code_generation | 618 | MIT | nlp_100_knocks | pythonを用いて、“Spain”の単語ベクトルから”Madrid”のベクトルを引き、”Athens”のベクトルを足したベクトルを計算し、そのベクトルと類似度の高い10語とその類似度を出力せよ。 | |
import pandas as pd
from gensim.models import KeyedVectors
from tqdm import tqdm
def culcSim(row):
global model
return pd.Series(list(model.most_similar(positive=[row['v2'], row['v3']], negative=[row['v1']])[0]))
tqdm.pandas()
df = pd.read_csv('ch07/questions-words.txt', sep=' ')
df = df.reset_index()
df.co... | code_generation | 619 | MIT | nlp_100_knocks | pythonを用いて、単語アナロジーの評価データをダウンロードし、vec(2列目の単語) - vec(1列目の単語) + vec(3列目の単語)を計算し、そのベクトルと類似度が最も高い単語と、その類似度を求めよ。求めた単語と類似度は、各事例の末尾に追記せよ。 | |
import pandas as pd
from gensim.models import KeyedVectors
from tqdm import tqdm
def culcSim(row):
global model
return pd.Series(list(model.most_similar(positive=[row['v2'], row['v3']], negative=[row['v1']])[0]))
tqdm.pandas()
df = pd.read_csv('ch07/questions-words.txt', sep=' ')
df = df.reset_index()
df.co... | code_generation | 620 | MIT | nlp_100_knocks | pythonを用いて、単語アナロジーの評価データをダウンロードし、vec(2列目の単語) - vec(1列目の単語) + vec(3列目の単語)を計算し、そのベクトルと類似度が最も高い単語と、その類似度を求めよ。求めた単語と類似度は、各事例の末尾に追記し、この実行結果を用い、意味的アナロジー(semantic analogy)と文法的アナロジー(syntactic analogy)の正解率を測定せよ。 | |
import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
from tqdm import tqdm
def cosSim(v1, v2):
return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
def culcCosSim(row):
global model
w1v = model[row['Word 1']]
w2v = model[row['Word 2']]
return cosSim(w1v, w2v... | code_generation | 621 | MIT | nlp_100_knocks | pythonを用いて、The WordSimilarity-353 Test Collectionの評価データをダウンロードし、単語ベクトルにより計算される類似度のランキングと、人間の類似度判定のランキングの間のスピアマン相関係数を計算せよ。 | |
import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
from sklearn.cluster import KMeans
# http://www.fao.org/countryprofiles/iso3list/en/
country = pd.read_table('ch07/countries.tsv')
country = country['Short name'].values
model = KeyedVectors.load_word2vec_format('ch07/GoogleNews-vectors-ne... | code_generation | 622 | MIT | nlp_100_knocks | pythonを用いて、国名に関する単語ベクトルを抽出し、k-meansクラスタリングをクラスタ数k=5として実行せよ。 | |
import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram
# http://www.fao.org/countryprofiles/iso3list/en/
country = pd.read_table('ch07/countries.tsv')
country = country['Short name'].values
model = KeyedVec... | code_generation | 623 | MIT | nlp_100_knocks | pythonを用いて、国名に関する単語ベクトルに対し、Ward法による階層型クラスタリングを実行せよ。さらに、クラスタリング結果をデンドログラムとして可視化せよ。 | |
import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
# http://www.fao.org/countryprofiles/iso3list/en/
country = pd.read_table('ch07/countries.tsv')
country = country['Short name'].values
model = KeyedVectors.load_word2vec_for... | code_generation | 624 | MIT | nlp_100_knocks | pythonを用いて、ベクトル空間上の国名に関する単語ベクトルをt-SNEで可視化せよ。 | |
import joblib
import numpy as np
import pandas as pd
from gensim.models import KeyedVectors
from tqdm import tqdm
def culcSwem(row):
global model
swem = [model[w] if w in model.vocab else np.zeros(shape=(model.vector_size,)) for w in row['TITLE'].split()]
swem = np.mean(np.array(swem), axis=0)
return ... | code_generation | 625 | MIT | nlp_100_knocks | pythonを用いて、手持ちの学習データ、検証データ、評価データを行列・ベクトルに変換したい。例えば、学習データについて、すべての事例$$x_i$$の特徴ベクトル$$\boldsymbol{x}_i$$を並べた行列$$X$$と、正解ラベルを並べた行列(ベクトル)$$Y$$を作成したい。
$$
X = \begin{pmatrix}
\boldsymbol{x}_1 \\
\boldsymbol{x}_2 \\
\dots \\
\boldsymbol{x}_n \\
\end{pmatrix} \in \mathbb{R}^{n \times d},
Y = \begin{pmatrix}
y_1 ... | |
import joblib
import numpy as np
import torch
import torch.nn as nn
X_train = joblib.load('ch08/X_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
X = X_train[0:4]
net = nn.Sequential(nn.Linear(X.size()[1], 4), nn.Softmax(1))
y_pred = net(X)
print(y_pred) | code_generation | 626 | MIT | nlp_100_knocks | pythonを用いて、以下の行列を読み込み、学習データについて以下の計算を実行せよ。
$$
\hat{\boldsymbol{y}}_1 = {\rm softmax}(\boldsymbol{x}_1 W), \\
\hat{Y} = {\rm softmax}(X_{[1:4]} W)
$$
ただし、$${\rm softmax}$$はソフトマックス関数、$$X_{[1:4]} \in \mathbb{R}^{4 \times d}$$は特徴ベクトル$$\boldsymbol{x}_1, \boldsymbol{x}_2, \boldsymbol{x}_3, \boldsymbol{x}_4$$を縦に並べた行列である。
$... | |
import joblib
import numpy as np
import torch
import torch.nn as nn
X_train = joblib.load('ch08/X_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
X = X_train[0:4]
net = nn.Sequential(nn.Linear(X.size()[1], 4), nn.Softmax(1))
y_pred = net(X)
print(y_pred) | code_generation | 627 | MIT | nlp_100_knocks | 学習データの事例$$x_1$$と事例集合$$x_1, x_2, x_3, x_4$$に対して、クロスエントロピー損失と、行列$$W$$に対する勾配を計算せよ。なお、ある事例$$x_i$$に対して損失は次式で計算される。
$$
l_i = - \log [\mbox{事例}x_i\mbox{が}y_i\mbox{に分類される確率}]
$$
ただし、事例集合に対するクロスエントロピー損失は、その集合に含まれる各事例の損失の平均とする。 | |
import joblib
import numpy as np
import torch
from torch import nn, optim
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)).clone()
X = X_train[0:4]
y = y_train[... | code_generation | 628 | MIT | nlp_100_knocks | pythonを用いて、確率的勾配降下法(SGD: Stochastic Gradient Descent)を用いて、行列W
を学習せよ。なお、学習は適当な基準で終了させればよい(例えば「100エポックで終了」など)。 | |
import joblib
import numpy as np
import torch
from torch import nn, optim
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)).clone()
X_test = joblib.load('ch08/X_... | code_generation | 629 | MIT | nlp_100_knocks | pythonを用いて、確率的勾配降下法(SGD: Stochastic Gradient Descent)を用いて、行列W
を学習し、求めた行列を用いて学習データおよび評価データの事例を分類したとき、その正解率をそれぞれ求めよ。 | |
import joblib
import numpy as np
import torch
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)).clone(... | code_generation | 630 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、各エポックのパラメータ更新が完了するたびに、訓練データでの損失、正解率、検証データでの損失、正解率をグラフにプロットし、学習の進捗状況を確認できるようにせよ。
import joblib
import numpy as np
import torch
from torch import nn, optim
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float3... | |
import joblib
import numpy as np
import torch
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)).clone(... | code_generation | 631 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、各エポックのパラメータ更新が完了するたびに、チェックポイント(学習途中のパラメータ(重み行列など)の値や最適化アルゴリズムの内部状態)をファイルに書き出せ。
import joblib
import numpy as np
import torch
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from... | |
import joblib
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.... | code_generation | 632 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、B事例ごとに損失・勾配を計算し、行列Wの値を更新せよ(ミニバッチ化)。Bの値を1,2,4,8,…と変化させながら、1エポックの学習に要する時間を比較せよ。
import joblib
import numpy as np
import torch
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_... | |
import joblib
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.... | code_generation | 633 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、GPU上で学習を実行せよ。
import joblib
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train ... | |
import joblib
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.... | code_generation | 634 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、バイアス項の導入や多層化など、ニューラルネットワークの形状を変更しながら、高性能なカテゴリ分類器を構築せよ。
import joblib
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn, optim
import matplotlib.pyplot as plt
X_train = joblib.load('ch08/X_train.joblib')
y_train = jo... | |
from torchtext import data
TEXT = data.Field(sequential=True, lower=True, batch_first=True)
LABELS = data.Field(sequential=False, batch_first=True, use_vocab=False)
train, valid, test = data.TabularDataset.splits(
path='ch06', train='train2.txt',
validation='valid2.txt', test='test2.txt', format='tsv',
f... | code_generation | 635 | MIT | nlp_100_knocks | pythonを用いて、手持ちの学習データ中の単語にユニークなID番号を付与したい。学習データ中で最も頻出する単語に`1`、2番目に頻出する単語に`2`、……といった方法で、学習データ中で2回以上出現する単語にID番号を付与せよ。そして、与えられた単語列に対して、ID番号の列を返す関数を実装せよ。ただし、出現頻度が2回未満の単語のID番号はすべて`0`とせよ。 | |
from torchtext import data
import torch
from torch import nn
class RNN(nn.Module):
def __init__(self, num_embeddings,
embedding_dim=50,
hidden_size=50,
output_size=1,
num_layers=1,
dropout=0.2):
super().__init__()
... | code_generation | 636 | MIT | nlp_100_knocks | pythonを用いて、ID番号で表現された単語列$$\boldsymbol{x} = (x_1, x_2, \dots, x_T)$$がある。ただし、$$T$$は単語列の長さ、$$x_t \in \mathbb{R}^{V}$$は単語のID番号のone-hot表記である($$V$$は単語の総数である)。再帰型ニューラルネットワーク(RNN: Recurrent Neural Network)を用い、単語列$$\boldsymbol{x}$$からカテゴリ$$y$$を予測するモデルとして、次式を実装せよ。
$$
\overrightarrow{h}_0 = 0, \\
\overrightarrow{h}_t = {\rm \over... | |
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
class BucketIteratorWrapper(DataLoader):
__initialized__ = False
def __in... | code_generation | 637 | MIT | nlp_100_knocks | pythonを用いて、確率的勾配降下法(SGD: Stochastic Gradient Descent)を用いて、問題81で構築したモデルを学習せよ。訓練データ上の損失と正解率、評価データ上の損失と正解率を表示しながらモデルを学習し、適当な基準(例えば10エポックなど)で終了させよ。 | |
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
class BucketIteratorWrapper(DataLoader):
__initialized__ = False
def __in... | code_generation | 638 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、$$B$$事例ごとに損失・勾配を計算して学習を行えるようにせよ($$B$$の値は適当に選べ)。また、GPU上で学習を実行せよ。
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterat... | |
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
from gensim.models import KeyedVectors
class BucketIteratorWrapper(DataLoader):
... | code_generation | 639 | MIT | nlp_100_knocks | pythonを用いて、事前学習済みの単語ベクトル(例えば、Google Newsデータセット(約1,000億単語)での[学習済み単語ベクトル](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing))で単語埋め込み$$\mathrm{emb}(x)$$を初期化し、学習せよ。 | |
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
from gensim.models import KeyedVectors
class BucketIteratorWrapper(DataLoader):
... | code_generation | 640 | MIT | nlp_100_knocks | pythonを用いて、順方向と逆方向のRNNの両方を用いて入力テキストをエンコードし、モデルを学習せよ。
$$
\overleftarrow{h}_{T+1} = 0, \\
\overleftarrow{h}_t = {\rm \overleftarrow{RNN}}(\mathrm{emb}(x_t), \overleftarrow{h}_{t+1}), \\
y = {\rm softmax}(W^{(yh)} [\overrightarrow{h}_T; \overleftarrow{h}_1] + b^{(y)})
$$
ただし、$$\overrightarrow{h}_t \in \mathbb{R}^{d_h}, ... | |
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchtext import data
from torch.utils.data import DataLoader
from torchtext.data import Iterator
from gensim.models import KeyedVectors
class BucketIteratorWrapper(DataLoader):
__initialized__ = False
def __init__(self, iterator: ... | code_generation | 641 | MIT | nlp_100_knocks | pythonを用いて、ID番号で表現された単語列$$\boldsymbol{x} = (x_1, x_2, \dots, x_T)$$がある。ただし、$$T$$は単語列の長さ、$$x_t \in \mathbb{R}^{V}$$は単語のID番号のone-hot表記である($$V$$は単語の総数である)。畳み込みニューラルネットワーク(CNN: Convolutional Neural Network)を用い、単語列$$\boldsymbol{x}$$からカテゴリ$$y$$を予測するモデルを実装せよ。
ただし、畳み込みニューラルネットワークの構成は以下の通りとする。
+ 単語埋め込みの次元数: $$d_w$$
+ 畳み込みのフィル... | |
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
from gensim.models import KeyedVectors
class Bucke... | code_generation | 642 | MIT | nlp_100_knocks | pythonを用いて、確率的勾配降下法(SGD: Stochastic Gradient Descent)を用いて、問題86で構築したモデルを学習せよ。訓練データ上の損失と正解率、評価データ上の損失と正解率を表示しながらモデルを学習し、適当な基準(例えば10エポックなど)で終了させよ。 | |
import torch
from torch import nn, optim
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.data import Iterator
from gensim.models import KeyedVectors
class BucketIteratorWrapper(DataLoader):
... | code_generation | 643 | MIT | nlp_100_knocks | pythonを用いて、以下のコードを改変し、ニューラルネットワークの形状やハイパーパラメータを調整しながら、高性能なカテゴリ分類器を構築せよ。
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchtext import data
from catalyst.dl import SupervisedRunner
from catalyst.dl.callbacks import AccuracyCallback
from torch.utils.data import DataLoader
from torchtext.... | |
from tqdm import tqdm
import torch
from torch import optim
from torchtext import data
from transformers import BertForSequenceClassification
def eval_net(model, data_loader, device='cpu'):
model.eval()
ys = []
ypreds = []
for x, y, _ in data_loader:
with torch.no_grad():
loss, logi... | code_generation | 644 | MIT | nlp_100_knocks | pythonを用いて、事前学習済み言語モデル(例えば[BERT](https://github.com/google-research/bert)など)を出発点として、ニュース記事見出しをカテゴリに分類するモデルを構築せよ。 | |
onmt_preprocess -train_src data/kyoto-train.ja -train_tgt data/kyoto-train.en -valid_src data/kyoto-dev.ja -valid_tgt data/kyoto-dev.en -save_data data/data -src_vocab_size 10000 -tgt_vocab_size 10000
onmt_train \
-data data/data \
-save_model data/demo-model \
-train_steps 100000 \
-world_size 1 \
-gpu_... | code_generation | 645 | MIT | nlp_100_knocks | shellscriptを用いて、機械翻訳のデータセットをダウンロードせよ。訓練データ、開発データ、評価データを整形し、必要に応じてトークン化などの前処理を行うこと。ただし、この段階ではトークンの単位として形態素(日本語)および単語(英語)を採用せよ。 | |
onmt_translate \
-model data/demo-model_step_100000.pt \
-src data/kyoto-test.ja \
-output pred.txt \
-replace_unk \
-verbose \
-gpu 0 | code_generation | 646 | MIT | nlp_100_knocks | shellscriptを用いて、手持ちのデータを用いて、ニューラル機械翻訳のモデルを学習せよ(ニューラルネットワークのモデルはTransformerやLSTMなど適当に選んでよい)。 | |
# https://forum.opennmt.net/t/simple-opennmt-py-rest-server/1392
export IP="0.0.0.0"
export PORT=5000
export URL_ROOT="/translator"
export CONFIG="./available_models/conf.json"
export HOST="127.0.0.1"
# NOTE that these parameters are optionnal
# here, we explicitely set to default values
python server.py --ip $IP --po... | code_generation | 647 | MIT | nlp_100_knocks | shellscriptを用いて、ニューラル機械翻訳モデルを用い、与えられた(任意の)日本語の文を英語に翻訳するプログラムを実装せよ。 | |
import numpy as np | code_generation | 648 | The Unliscence | 100_numpy_exercises | numpyパッケージを "np" という名前でインポートしなさい。 | |
print(np.__version__)
np.show_config() | code_generation | 649 | The Unliscence | 100_numpy_exercises | numpyのバージョンと設定を表示しなさい。 | |
Z = np.zeros(10)
print(Z) | code_generation | 650 | The Unliscence | 100_numpy_exercises | numpyを用いて、サイズ10の空行列を作成しなさい。 | |
print("%d bytes" % (Z.size * Z.itemsize)) | code_generation | 651 | The Unliscence | 100_numpy_exercises | numpyを用いて、次に示す配列のメモリサイズを調べなさい。
Z = np.zeros((10,10)) | |
%run `python -c "import numpy; numpy.info(numpy.add)"` | code_generation | 652 | The Unliscence | 100_numpy_exercises | コマンドラインからnumpy add関数のドキュメントを取得しなさい。 | |
Z = np.zeros(10)
Z[4] = 1
print(Z) | code_generation | 653 | The Unliscence | 100_numpy_exercises | numpyを用いて、サイズ10の空行列を作成しなさい。ただし、5番目の値は1である。 | |
Z = np.arange(10,50)
print(Z) | code_generation | 654 | The Unliscence | 100_numpy_exercises | numpyを用いて、10から49までの値を持つベクトルを作成しなさい。 | |
Z = Z[::-1]
print(Z) | code_generation | 655 | The Unliscence | 100_numpy_exercises | numpyを用いて、次に示すベクトルを逆にしなさい(最初の要素が最後の要素になる)。
Z = np.arange(50) | |
Z = np.arange(9).reshape(3, 3)
print(Z) | code_generation | 656 | The Unliscence | 100_numpy_exercises | numpyを用いて、0から8までの値を持つ3x3の行列を作成する。 | |
nz = np.nonzero([1,2,0,0,4,0])
print(nz) | code_generation | 657 | The Unliscence | 100_numpy_exercises | numpyを用いて、[1,2,0,0,4,0]から非ゼロ要素のインデックスを見つけなさい。 | |
Z = np.eye(3)
print(Z) | code_generation | 658 | The Unliscence | 100_numpy_exercises | numpyを用いて、3x3の恒等行列を作りなさい。 | |
Z = np.random.random((3,3,3))
print(Z) | code_generation | 659 | The Unliscence | 100_numpy_exercises | numpyを用いて、ランダムな値で3x3x3の配列を作成しなさい。 | |
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax) | code_generation | 660 | The Unliscence | 100_numpy_exercises | numpyを用いて、ランダムな値で10x10の配列を作成し、最小値と最大値を求めなさい。 | |
Z = np.random.random(30)
m = Z.mean()
print(m) | code_generation | 661 | The Unliscence | 100_numpy_exercises | numpyを用いて、サイズ30のランダムなベクトルを作成し、平均値を求めなさい。 | |
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z) | code_generation | 662 | The Unliscence | 100_numpy_exercises | numpyを用いて、境界線上に1、内側に0を持つ2次元配列を作成しなさい。 | |
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z) | code_generation | 663 | The Unliscence | 100_numpy_exercises | numpyを用いて、既存の配列の周囲にボーダー(0で塗りつぶされたもの)を追加しなさい。 | |
print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1) | code_generation | 664 | The Unliscence | 100_numpy_exercises | 次の6つの式の結果を表示して下さい。
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1 | |
Z = np.diag(1+np.arange(4),k=-1)
print(Z) | code_generation | 665 | The Unliscence | 100_numpy_exercises | numpyを用いて、対角線のすぐ下に値1,2,3,4を持つ5x5の行列を作成しなさい。 | |
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z) | code_generation | 666 | The Unliscence | 100_numpy_exercises | numpyを用いて、8x8のマトリックスを作成し、市松模様で塗りつぶしなさい。 | |
print(np.unravel_index(99,(6,7,8))) | code_generation | 667 | The Unliscence | 100_numpy_exercises | numpyを用いて、(6,7,8)型の配列を考えよう。100番目の要素のインデックス(x,y,z)は? | |
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z) | code_generation | 668 | The Unliscence | 100_numpy_exercises | numpyのtile関数を用いて、8x8のチェッカーボード行列を作りなさい。 | |
Z = np.random.random((5,5))
Z = (Z - np.mean (Z)) / (np.std (Z))
print(Z) | code_generation | 669 | The Unliscence | 100_numpy_exercises | numpyを用いて、5x5のランダム行列を正規化しなさい。 | |
color = np.dtype([("r", np.ubyte),
("g", np.ubyte),
("b", np.ubyte),
("a", np.ubyte)]) | code_generation | 670 | The Unliscence | 100_numpy_exercises | numpyを用いて、色を4つの符号なしバイト(RGBA)として記述するカスタムd型を作成しなさい。 | |
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# Alternative solution, in Python 3.5 and above
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z) | code_generation | 671 | The Unliscence | 100_numpy_exercises | numpyを用いて、5x3の行列と3x2の行列の乗算をしなさい。 | |
Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z) | code_generation | 672 | The Unliscence | 100_numpy_exercises | numpyを用いて、1次元の配列が与えられたとき、3から8までの要素をすべて無効にしなさい。 | |
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1)) | code_generation | 673 | The Unliscence | 100_numpy_exercises | 次のスクリプトの出力は?
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1)) | |
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z | code_generation | 674 | The Unliscence | 100_numpy_exercises | numpyを用いて、整数ベクトルZを考えてみよう。 | |
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float)) | code_generation | 675 | The Unliscence | 100_numpy_exercises | 次の式の結果を表示しなさい。
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float) | |
Z = np.random.uniform(-10,+10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))
# More readable but less efficient
print(np.where(Z>0, np.ceil(Z), np.floor(Z))) | code_generation | 676 | The Unliscence | 100_numpy_exercises | numpyを用いて、浮動小数点数の配列をゼロから切り捨てなさい。
Z = np.random.uniform(-10,+10,10) | |
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2)) | code_generation | 677 | The Unliscence | 100_numpy_exercises | numpyを用いて、2つの配列間の共通値を見つけなさい。
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10) | |
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
# Back to sanity
_ = np.seterr(**defaults)
# Equivalently with a context manager
with np.errstate(all="ignore"):
np.arange(3) / 0 | code_generation | 678 | The Unliscence | 100_numpy_exercises | numpyの警告をすべて無視するには? | |
False | code_generation | 679 | The Unliscence | 100_numpy_exercises | 次の表現は正しいですか?
np.sqrt(-1) == np.emath.sqrt(-1) | |
yesterday = np.datetime64('today') - np.timedelta64(1)
today = np.datetime64('today')
tomorrow = np.datetime64('today') + np.timedelta64(1) | code_generation | 680 | The Unliscence | 100_numpy_exercises | numpyを用いて、昨日、今日、明日の日付を取得するには? | |
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z) | code_generation | 681 | The Unliscence | 100_numpy_exercises | numpyを用いて、2016年7月に対応するすべての日付を取得するには? | |
A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A) | code_generation | 682 | The Unliscence | 100_numpy_exercises | numpyを用いて、((A+B)*(-A/2))をコピーなしで計算しなさい。 | |
Z = np.random.uniform(0,10,10)
print(Z - Z%1)
print(Z // 1)
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z)) | code_generation | 683 | The Unliscence | 100_numpy_exercises | numpyを用いて、正数のランダム配列の整数部分を4つの異なる方法で抽出しなさい。 | |
Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)
# without broadcasting
Z = np.tile(np.arange(0, 5), (5,1))
print(Z) | code_generation | 684 | The Unliscence | 100_numpy_exercises | numpyを用いて、行の値が0から4までの5x5の行列を作成しなさい。 | |
def generate():
for x in range(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z) | code_generation | 685 | The Unliscence | 100_numpy_exercises | numpyを用いて、10個の整数を生成するジェネレーター関数を考え、それを使って配列を構築しなさい。 | |
Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z) | code_generation | 686 | The Unliscence | 100_numpy_exercises | numpyを用いて、0から1までの値を持つ、サイズ10のベクトルを作成しなさい。 | |
Z = np.random.random(10)
Z.sort()
print(Z) | code_generation | 687 | The Unliscence | 100_numpy_exercises | numpyを用いて、サイズ10のランダムなベクトルを作成し、それをソートしなさい。 | |
Z = np.arange(10)
np.add.reduce(Z) | code_generation | 688 | The Unliscence | 100_numpy_exercises | numpyを用いて、小さな配列をnp.sumより高速に合計するには? | |
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal) | code_generation | 689 | The Unliscence | 100_numpy_exercises | numpyを用いて、2つのランダムな配列AとBを考え、それらが等しいかどうかをチェックしなさい。
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5) | |
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1 | code_generation | 690 | The Unliscence | 100_numpy_exercises | numpyを用いて、配列をイミュータブル(読み取り専用)にしなさい。 | |
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T) | code_generation | 691 | The Unliscence | 100_numpy_exercises | numpyを用いて、デカルト座標を表すランダムな10x2行列を考え、極座標に変換しなさい。 | |
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z) | code_generation | 692 | The Unliscence | 100_numpy_exercises | numpyを用いて、サイズ10のランダム・ベクトルを作成し、最大値を0に置き換えなさい。 | |
Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z) | code_generation | 693 | The Unliscence | 100_numpy_exercises | numpyを用いて、[0,1]x[0,1]の領域をカバーする x と y の座標を持つ構造化配列を作成しなさい。 | |
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C)) | code_generation | 694 | The Unliscence | 100_numpy_exercises | numpyを用いて、2つの配列XとYが与えられたとき、コーシー行列C(Cij =1/(xi - yj))を構成しなさい。 | |
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps) | code_generation | 695 | The Unliscence | 100_numpy_exercises | numpyを用いて、各numpyスカラ型の表現可能な最小値と最大値を表示しなさい。 | |
np.set_printoptions(threshold=float("inf"))
Z = np.zeros((40,40))
print(Z) | code_generation | 696 | The Unliscence | 100_numpy_exercises | numpyを用いて、配列のすべての値を表示しなさい。 | |
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index]) | code_generation | 697 | The Unliscence | 100_numpy_exercises | numpyを用いて、ベクトルの中で(与えられたスカラーに)最も近い値を見つけなさい。
Z = np.arange(100)
v = np.random.uniform(0,100) | |
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
print(Z) | code_generation | 698 | The Unliscence | 100_numpy_exercises | numpyを用いて、位置(x,y)と色(r,g,b)を表す構造化配列を作成しなさい。 | |
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
# Much faster with scipy
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D) | code_generation | 699 | The Unliscence | 100_numpy_exercises | numpyを用いて、座標を表す形状(10,2)のランダムなベクトルを考え、点ごとの距離を求めなさい。 |
Subsets and Splits
Python Code Generation
Provides a structured view of code generation tasks specific to a Python-focused course, helping to understand the nature and sequence of the instructions and outputs.
Filtered Code Generation Tasks
The query extracts code generation questions and answers from a specific dataset source, offering structured insights into its contents.
Code Generation Instruction Split
The query processes and splits code generation outputs into separate answers, providing a structured view of potential alternative solutions for each instruction.
Filtered Code Generation Task
The query performs basic filtering and returns formatted data related to code generation tasks, which is helpful but does not provide deep insights into the dataset's underlying structure or patterns.
Code Generation Instructions
The query performs basic filtering to select code generation tasks and organizes them by license, source, and index, providing a simple overview but lacking deeper analytical insight.
Code Generation Instructions
The query performs basic filtering and selects specific columns, providing limited insight into the dataset's structure but not revealing deeper patterns or relationships.
Code Generation Instructions
The query performs basic filtering and selection, organizing code generation tasks by license and source but does not provide deep insights into the data.
^_Call_Call:::^_Call_Call:
The query performs basic filtering and selection, organizing code generation tasks by license, source, and index without revealing deeper insights.
^^^_Call.FromSeconds:^^ withheld^
The query performs basic filtering and ordering of dataset entries, providing a structured view but lacking deeper insights.
_Call^^^^^ serotonin^:^
The query performs basic data retrieval and organization, presenting specific fields in a structured format but without providing significant analytical insights.