【Python】How to find the percentile scores of a numpy array? - 101 Numpy Exercises
Q:
irisデータの"sepallength"の5~95パーセンタイルを見つけなさい
A:
# Input url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0]) # Solution np.percentile(sepallength, q=[5, 95]) #> array([ 4.6 , 7.255])
【C#】リストから指定した値に一番近い値を持つインデックスを取得する
例えば以下のようなことがやりたく、普段for文を回してサーチしていました。
var list = new List<double>() { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; double value = 3.1; int index = FindClosestIndex(list, value); // 3.1に一番近い値は3.0。3.0のインデックスは2なので2と表示される Console.WriteLine(index);
このやり方はStackOverflowにあって、下記で出来ました。Aggregateは分かりづらいので放っておいたのですが、こんな使い方も出来るのですね。
int FindClosestIndex(List<double> list, double value) { double closest = list.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y); return list.IndexOf(closest); }
【Python】How to extract a particular column from 1D array of tuples? - 101 Numpy Exercises
Q:
irisデータのspeciesカラムを取り出しなさい
A:
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris_1d = np.genfromtxt(url, delimiter=',', dtype=None) species = np.array([row[4] for row in iris_1d]) species[:5] #> array([b'Iris-setosa', b'Iris-setosa', b'Iris-setosa', b'Iris-setosa', #> b'Iris-setosa'], #> dtype='|S18')
【Python】How to print only 3 decimal places in python numpy array? - 101 Numpy Exercises
Q:
小数点を三桁のみ表示するようにしなさい
A:
# Create the random array rand_arr = np.random.random([5,3]) # Limit to 3 decimal places np.set_printoptions(precision=3) rand_arr[:4] #> array([[ 0.443, 0.109, 0.97 ], #> [ 0.388, 0.447, 0.191], #> [ 0.891, 0.474, 0.212], #> [ 0.609, 0.518, 0.403]])
【Python】How to swap two columns in a 2d numpy array? - 101 Numpy Exercises
Q:
変数arrのカラム0とカラム1を入れ替えなさい
arr = np.arange(9).reshape(3,3) #> array([[0, 1, 2], #> [3, 4, 5], #> [6, 7, 8]])
A:
arr = arr[:, [1, 0, 2]] #> array([[1, 0, 2], #> [4, 3, 5], #> [7, 6, 8]])
【Python】How to replace items that satisfy a condition without affecting the original array? - 101 Numpy Exercises
Q:
0~9の奇数を元の変数に影響を与えずに-1に変更する
A:
import numpy as np arr = np.arange(0, 10) arr_ = np.where(arr%2 == 1, -1, arr)
【Python】KerasでMobileNetのモデルファイルを読み込む方法
KerasでMobileNetのモデルファイルを読み込もうとすると"Unknown activation function:relu6"といったエラーが出ます。このエラーへの対処はここに書かれており、以下のようにすれば大丈夫でした。
from keras.utils.generic_utils import CustomObjectScope with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6,'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}): model = load_model('weights.h5')