Exemple #1
0
def main():
    # 機械学習オブジェクトを生成(復元)
    clf = mc.load(mc.default_path)

    # 特徴生成オブジェクト作成
    fg_obj = feature.feature_generator(23)

    predict(
        clf,
        date_range(datetime.datetime(2015, 6, 23),
                   datetime.datetime(2015, 10, 24)), fg_obj, True)
def sub_process2(target_dir, feature_generator, terms):
    """ 保存されている学習器を次々と読みだして評価結果をファイルに保存する
    target_dir: str, 学習器が保存されたフォルダ名
    feature_generator: 特徴ベクトルを作成するクラス
    terms: list, 処理期間を格納したリスト。要素はタプル。要素の数は複数あっても良い。
    """
    flist = mc.get_path_list(target_dir) # 学習器のファイルリストを取得
    print(flist)
    if len(flist) == 0:
        print("0 files or dir found.")
        return

    # 正解データと特徴ベクトルを取得
    data = read_correct_and_create_features(feature_generator, terms)
    dates = sorted(data.keys())

    # 正解のカウントと計算条件のチェック
    correct = [int(data[_date][0]) for _date in dates]
    print("correct: ", correct)
    amount_of_positive = correct.count(1)
    amount_of_negative = correct.count(0)
    if amount_of_positive == 0 or amount_of_negative == 0:    # いずれかが0であれば、計算する意味が無い
        print("amount of positive/negative is 0. So, fin.")
        return

    # 評価用に特徴ベクトルを辞書に格納しなおす
    features = np.array([data[_date][2] for _date in dates])  # 特徴を入れた2次元配列

    # 予想結果を格納する
    predicted_result_dict = {}
    for fpath in flist:
        print("--scoring... now target is {0}--".format(fpath))
        clf = mc.load(fpath)    # オブジェクト復元
        y_score = clf.predict(features)
        predicted_result_dict[fpath] = y_score

    # AUCを求め、結果をファイルに保存    
    auc_report = target_dir + "/learned_machine_report_auc.csv"
    y_true = np.array([int(data[_date][0]) for _date in dates])
    auc_max = (0, "")
    with open(auc_report, "w") as fw_auc:
        for fpath in flist:
            y_score = predicted_result_dict[fpath]

            fpr, tpr, thresholds = mtr.roc_curve(y_true, y_score, pos_label=1)   # ftr: false_positive,  tpr: true_positive
            auc = mtr.auc(fpr, tpr)

            fw_auc.write("{0},{1}\n".format(fpath, auc))
            if auc_max[0] < auc:
                auc_max = (auc, fpath)
        fw_auc.write("AUC max:{0},{1}\n".format(auc_max[1], auc_max[0]))
        print("AUC max:", auc_max)
def main():
	# 機械学習オブジェクトを生成(復元)
	clf = mc.load(mc.default_path)

	# 特徴生成オブジェクト作成
	fg_obj = feature.feature_generator(23)

	predict(
		clf, 
		date_range(datetime.datetime(2015, 6, 23), datetime.datetime(2015, 10, 24)), 
		fg_obj, 
		True
		)
Exemple #4
0
def main(argv):
    if len(argv) <= 1:
        return 1

    fd = rfile.create_file(argv[1], 'rb')
    try:
        source = fd.read()
    finally:
        fd.close()

    code, next_varno = parser.parse(source)
    program = machine.load(code)
    succ = machine.Success()
    try:
        program.solve(succ, Compound(MAIN, []), next_varno)
    except machine.Exiting as exit:
        return exit.status
    return 0
def sub_process(tag_name, target_dir, feature_generator, terms):
	""" 保存されている学習器を次々と読みだして評価結果をファイルに保存する
	"""
	flist = mc.get_path_list(target_dir) # 学習器のファイルリストを取得
	print(flist)
	if len(flist) == 0:
		print("0 files or dir found.")
		return

	# 正解データと特徴ベクトルを取得
	data = read_correct_and_create_features(feature_generator, terms)

	# 評価用に特徴ベクトルを辞書に格納しなおす
	dates = sorted(data.keys())
	features_dict = {}                                      # 日付をキーとした特徴ベクトル
	for _date in dates:
		features_dict[_date] = (None, data[_date][2], None) # 特徴ベクトルが欲しいだけなので前後をダミーデータを入れている

	# 予想結果を格納する
	predicted_result_dict = {}
	for fpath in flist:
		# 学習器を読みだして復元
		clf = mc.load(fpath)    # オブジェクト復元
		predicted_result = predict.predict2(clf, dates, features_dict)
		predicted_result_dict[fpath] = predicted_result

	# 結果をファイルに保存
	report_path = target_dir + "/learned_machine_report.csv"
	with open(report_path, "w") as fw:
		# 閾値を変えつつ集計
		for th in numpy.arange(0.4, 0.9, 0.2): # th: 閾値
			result = {}                        # 閾値で2値化した結果を格納する
			correct = []
			for fpath in flist:
				predicted_result = predicted_result_dict[fpath]
				if fpath not in result:
					result[fpath] = []
				correct = []
				for _date in dates:
					if _date in predicted_result:
						c = data[_date][0]
						correct.append(c)
						val = float(c) - int((1.0 - th) + predicted_result[_date])
						result[fpath].append(val)

			# 日付を書き込む
			dates_arr = [str(x) for x in dates]
			_str = ",".join(dates_arr)
			fw.write(",date,")
			fw.write(_str)
			fw.write("\n")
			# 正解を書き込む
			correct = [str(c) for c in correct]
			_str = ",".join(correct)
			fw.write(",correct,")
			fw.write(_str)
			fw.write("\n")
			# 結果を書き込む
			for fpath in flist:
				th_data = result[fpath]
				th_data = [str(x) for x in th_data]
				_str = ",".join(th_data)
				fw.write(fpath)          # Excelで閲覧した時に分離させる
				fw.write(",")
				fw.write(str(th))
				fw.write(",")
				fw.write(_str)
				fw.write("\n")
	return report_path
def sub_process2(tag_name, target_dir, feature_generator, terms):
	""" 保存されている学習器を次々と読みだして評価結果をファイルに保存する
	"""
	flist = mc.get_path_list(target_dir) # 学習器のファイルリストを取得
	print(flist)
	if len(flist) == 0:
		print("0 files or dir found.")
		return

	# 正解データと特徴ベクトルを取得
	data = read_correct_and_create_features(feature_generator, terms)
	dates = sorted(data.keys())

	# 正解のカウントと計算条件のチェック
	correct = [int(data[_date][0]) for _date in dates]
	print("correct: ", correct)
	amount_of_positive = correct.count(1)
	amount_of_negative = correct.count(0)
	if amount_of_positive == 0 or amount_of_negative == 0: # いずれかが0であれば、計算する意味が無い
		print("amount of positive/negative is 0. So, fin.")
		return

	# 評価用に特徴ベクトルを辞書に格納しなおす
	features_dict = {}                                      # 日付をキーとした特徴ベクトル
	for _date in dates:
		features_dict[_date] = (None, data[_date][2], None) # 特徴ベクトルが欲しいだけなので前後をダミーデータを入れている

	# 予想結果を格納する
	predicted_result_dict = {}
	for fpath in flist:
		# 学習器を読みだして復元
		clf = mc.load(fpath)    # オブジェクト復元
		predicted_result = predict.predict2(clf, dates, features_dict, save=False, feature_display=False) # 何が返ってくるか忘れないために、一度変数に入れている。
		predicted_result_dict[fpath] = predicted_result

	# AUCを求め、結果をファイルに保存	
	roc_report = target_dir + "/learned_machine_report_roc.csv"
	auc_report = target_dir + "/learned_machine_report_auc.csv"
	auc_max = (0, "")
	with open(roc_report, "w") as fw_roc, open(auc_report, "w") as fw_auc:
		for fpath in flist:
			predicted_result = predicted_result_dict[fpath]
			# 閾値を変えつつ集計
			tpr_array = []
			fpr_array = []
			for th in numpy.arange(0.1, 1.0, 0.05): # th: 閾値
				tp = 0 # true positive
				fp = 0 # false positive
				for _date in dates:
					c = int(data[_date][0])
					result = int((1.0 - th) + predicted_result[_date] + 0.0001)
					if c == 0 and result == 1:
						fp += 1
					elif c == 1 and result == 1:
						tp += 1
				tp_rate = tp / amount_of_positive
				fp_rate = fp / amount_of_negative
				tpr_array.append(tp_rate)
				fpr_array.append(fp_rate)

				fw_roc.write("{0},{1},{2},{3}\n".format(fpath, th, fp_rate, tp_rate))

			# AUC(ROC曲線の下の面積)を求める
			tpr_array.append(0)
			fpr_array.append(0)
			_x, _y, auc = 1, 1, 0
			for x, y in zip(fpr_array, tpr_array):
				w = _x - x
				auc += (y + _y) * w / 2 # 台形積分
				_x = x
				_y = y
			fw_auc.write("{0},{1}\n".format(fpath, auc))
			if auc_max[0] < auc:
				auc_max = (auc, fpath)
		fw_auc.write("AUC max:{0},{1}\n".format(auc_max[1], auc_max[0]))
		print("AUC max:", auc_max)
	return roc_report # この返り値には何の意味があったっけ?
def main():
	# 予想したい日の日付けを設定
	target_date = None
	_day = dt.now()        # まずはコマンドライン引数による指定がない場合を想定
	if _day.hour >= 10:    # この時刻を過ぎると、翌日の予想を実施する
		_day += td(days=1)
	target_date = dt(year=_day.year, month=_day.month, day=_day.day)

	argvs = sys.argv       # コマンドライン引数を格納したリストの取得
	argc = len(argvs)      # 引数の個数
	if argc >= 2:          # 引数で計算対象の日を渡す
		arg = argvs[1]
		arg += " 0:0:0"    # 時分秒を加える
		t = timeKM.getTime(arg)
		if t != None:
			target_date = t	
	print(target_date)

	# 予測を実行する時刻を決定する(引数がなければスクリプト実行時の時刻が使われる)
	process_hour = dt.now().hour
	if argc >= 3:          # 引数で予想実行時刻を渡す(その時刻に雲海が出るかを確認するものではない)
		arg = argvs[2]
		if arg.isdigit():
			process_hour = int(arg)

	# 予報する対象の時刻
	target_time = 23
	if 23 > process_hour >= 16:
		target_time = 16


	# アメダスの観測所オブジェクトを作成
	amedas_nodes = amd.get_amedas_nodes()
	#print(amedas_nodes)
	# 特徴ベクトルを生成するオブジェクトの用意
	features_dict = {}
	for block_no in ["47819", "1240", "0962", "47818"]:
		node = amedas_nodes[block_no]
		lines = get_amedas_data(node, target_date)
		weather_data = feature.get_weather_dict(lines)
		_keys = sorted(weather_data.keys())       # 確認のために表示
		for a_key in _keys:
			print(block_no, weather_data[a_key])
		if int(node.block_no) > 47000:
			features_dict[block_no] = [weather_data, feature.index_A]
		else:
			features_dict[block_no] = [weather_data, feature.index_B]
	fg_obj = feature.feature_generator(target_time, features_dict)

	# 機械学習オブジェクトを生成
	clf = mc.load(os.path.abspath("./learned_machine/time" + str(target_time)))
	print(type(clf))

	# 特徴ベクトルを生成
	_feature = fg_obj.get_feature(target_date)
	_feature = np.array([_feature]) # TensorFlowはnumpy.arrayの2重の入れ子でないと動かない
	print(_feature)

	# 予測を実施
	print("--predict--")
	print("target date: " + str(target_date))
	print("process hur: " + str(process_hour))

	results = []
	#if _feature != None:
	#if not None in _feature:  # Noneがあると計算出来ない
	test = clf.predict(_feature)
	results.append((target_date, test[0], _feature))
	print(test)


	# 予測結果を保存
	with open("result.csv", "w") as fw:
		for result in results:
			_date, predict_result, _feature = result
			str_feature = [str(x) for x in _feature]
			fw.write(str(dt.now()))
			fw.write(",")
			fw.write(str(_date))
			fw.write(",")
			fw.write(str(predict_result))
			fw.write(",")
			fw.write("$")
			fw.write(",")
			fw.write(",".join(str_feature))
			fw.write("\n")

	return results