Harigami
ログイン
Harigamiは、ログイン不要のコード共有サービスです。コードの投稿後に発行されるURLでコードを共有できます。
PythonやRubyなど一部の言語は、投稿後にオンラインで実行することもできます。
誰でも無料で使えて、広告もありません。コードレビューやスニペットの代わりに使ってみてください。


詳細設定
+
anonymous タイトルなし
Python
    private void moveToWrapper(double pos_x, double pos_y, double pos_z, double qua_x, double qua_y, double qua_z, double qua_w) {
        final int LOOP_MAX = 20;
        final Point point = new Point(pos_x, pos_y, pos_z);
        final Quaternion quaternion = new Quaternion((float) qua_x, (float) qua_y, (float) qua_z, (float) qua_w);
        Result result = api.moveTo(point, quaternion, true);
        int loopCounter = 0;
        while (!result.hasSucceeded() && loopCounter < LOOP_MAX) {
            result = api.moveTo(point, quaternion, true);
            ++loopCounter;
        }
    }
  • 0
  • 0
anonymous タイトルなし
VisualBasic
Imports System.Data.Odbc
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.ControlChars
Imports System.IO

Module Module1

Sub Main()

        Dim con As New System.Data.Odbc.OdbcConnection
        Dim command As New System.Data.Odbc.OdbcCommand
        Dim SyainTable As New DataTable


        '接続文字列
        con.ConnectionString = "DSN=TESTDB"

            'DBを開く
            con.Open()


            'トランザクション開始
            Dim tran As OdbcTransaction
            tran = con.BeginTransaction

            'SQLコマンド作成
            Dim sqlCom As New OdbcCommand

        Try


            '列項目作成(社員マスタテーブル)
            SyainTable.Columns.Add("社員コード", Type.GetType("System.String"))           '社員コード/ 文字列型
            SyainTable.Columns.Add("社員氏名", Type.GetType("System.String"))             '社員氏名  / 文字列型
            SyainTable.Columns.Add("社員英語", Type.GetType("System.String"))             '社員英語  / 文字列型
            SyainTable.Columns.Add("部門コード", Type.GetType("System.String"))           '部門コード/ 文字列型
            SyainTable.Columns.Add("部門名", Type.GetType("System.String"))               '部門名    / 文字列型
            SyainTable.Columns.Add("入社年月日", Type.GetType("System.DateTime"))         '入社年月日/ 日付型
            SyainTable.Columns.Add("年次", Type.GetType("System.DateTime"))               '年次      / 日付型
            SyainTable.Columns.Add("更新日時", Type.GetType("System.DateTime"))           '更新日時  / 日付型


            'command = con.CreateCommand



            'SQLクエリ
            Dim strSQL As String
            strSQL = ""
            strSQL = strSQL & "INSERT INTO "
            strSQL = strSQL & "社員マスタ "
            strSQL = strSQL & "("
            strSQL = strSQL & "社員コード, "
            strSQL = strSQL & "社員氏名, "
            strSQL = strSQL & "社員英語, "
            strSQL = strSQL & "部門コード, "
            strSQL = strSQL & "入社年月日, "
            strSQL = strSQL & "更新日時"
            strSQL = strSQL & ")"
            strSQL = strSQL & "VALUES"
            strSQL = strSQL & "("
            strSQL = strSQL & "?, "
            strSQL = strSQL & "?, "
            strSQL = strSQL & "?, "
            strSQL = strSQL & "?, "
            strSQL = strSQL & "?, "
            strSQL = strSQL & "?"
            strSQL = strSQL & ") "


            sqlCom = New OdbcCommand(strSQL, con)



            'パラメータ定義
            With sqlCom
                .Parameters.Add("@社員コード", OdbcType.VarChar)
                .Parameters.Add("@社員氏名", OdbcType.VarChar)
                .Parameters.Add("@社員英語", OdbcType.VarChar)
                .Parameters.Add("@部門コード", OdbcType.VarChar)
                .Parameters.Add("@入社年月日", OdbcType.VarChar)
                .Parameters.Add("@更新日時", OdbcType.VarChar)
            End With


            sqlCom.Transaction = tran

            Try


                '【重複用】sample.datの登録処理
                ' 重複ファイル パス定義
                Dim chohukuFile As String
                chohukuFile = "C:\Users\【重複用】sample.dat"

                Dim reader As New IO.StreamReader(chohukuFile, System.Text.Encoding.GetEncoding("shift_jis"))

                'ファイルの1行
                Dim line As String
                '行の項目の配列
                Dim item() As String
                '1行読んで何もしない(ヘッダーを飛ばす)
                line = reader.ReadLine
                '次の行を読む
                line = reader.ReadLine

                '1行が無くなるまでループ
                Do Until IsNothing(line)

                    'タブで区切る
                    item = line.Split(Tab)

                    'もし社員コードが5桁に満たない場合、左0埋めの5桁形式にする
                    If item(0).Length <= 5 Then

                        item(0) = item(0).PadLeft(5, "0")

                    End If

                    'もし部門コードが3桁に満たない場合、左0埋めの3桁形式にする
                    If item(3).Length <= 3 Then

                        item(3) = item(3).PadLeft(3, "0")

                    End If

                    '次の行を読む
                    line = reader.ReadLine
                Loop

                reader.Close()




                'sample.datファイルの存在チェック
                Dim addFile As String = "C:\Users\sample.dat"
                'sample.datファイルが存在する時の処理
                If System.IO.File.Exists(addFile) Then

                    For s As Integer = 1 To 1

                        'パラメータ追加
                        With sqlCom
                            .Parameters("@社員コード").Value = "00004"
                            .Parameters("@社員氏名").Value = "追加 太郎"
                            .Parameters("@社員英語").Value = "taro tsuika"
                            .Parameters("@部門コード").Value = "001"
                            .Parameters("@入社年月日").Value = "2004/04/01"
                            .Parameters("@更新日時").Value = "2020/02/01"
                        End With
                        'SQL実行
                        sqlCom.ExecuteNonQuery()


                        With sqlCom
                            .Parameters("@社員コード").Value = "00005"
                            .Parameters("@社員氏名").Value = "追加 花子"
                            .Parameters("@社員英語").Value = "Hanako Tsuika"
                            .Parameters("@部門コード").Value = "001"
                            .Parameters("@入社年月日").Value = "2005/10/01"
                            .Parameters("@更新日時").Value = "2020/02/02"
                        End With
                        'SQL実行
                        sqlCom.ExecuteNonQuery()


                        With sqlCom
                            .Parameters("@社員コード").Value = "00006"
                            .Parameters("@社員氏名").Value = "追加 次郎"
                            .Parameters("@社員英語").Value = "JIRO tsuika"
                            .Parameters("@部門コード").Value = "002"
                            .Parameters("@入社年月日").Value = "2006/09/01"
                            .Parameters("@更新日時").Value = "2020/01/31"
                        End With
                        'SQL実行
                        sqlCom.ExecuteNonQuery()


                    Next

                    'コミットする
                    sqlCom.Transaction.Commit()
                    MessageBox.Show("データの更新が完了しました。", "通知")

                Else

                    MessageBox.Show("該当フォルダにadd.datファイルが存在しません", "通知")

                End If

            Catch ex As Exception

                'ロールバック
                tran.Rollback()
                'エラーメッセージ
                MessageBox.Show("SQL実行箇所でのエラーです", "エラー")

            End Try



            'DataTableの中身を出力する処理
            'datファイルパス定義
            Dim FilePath As String
            FilePath = "output.dat"

            'output.datに出力
            '書き込むファイルを開く
            Dim sw As New System.IO.StreamWriter(FilePath, False, System.Text.Encoding.GetEncoding("shift_jis"))

            Dim colCount As Integer = SyainTable.Columns.Count
            Dim lastColIndex As Integer = colCount - 1

            'ヘッダを書き込む
            Dim i As Integer
            For i = 0 To colCount - 1

                'ヘッダの取得
                Dim field As String = SyainTable.Columns(i).Caption
                'フィールドを書きこむ
                sw.Write(field)

                Debug.Print("現在のfieldの値は" & field)

                'タブ区切りで書き込む
                If lastColIndex > i Then

                    sw.Write(Tab)

                End If

            Next

            '改行する
            sw.WriteLine()


            'レコードを書き込む
            For Each row In SyainTable.Rows

                ' ====== 入社年月日をyy年mm月の表記にする ======
                Dim Nyusya As DateTime
                Nyusya = row("入社年月日")
                ' ====== 更新日時をyy年mm月dd日の表記にする ======
                Dim Kosin As DateTime
                Kosin = row("更新日時")

                '====== 年次を算出する ======
                '現在の日時取得

                Dim dtNow As Date = Now
                '====== テスト太郎の入社年月日 ======
                Dim TaroDay As Date = "2001/4/1"
                ' 年を求める
                Dim TaroYear As Integer
                TaroYear = DateDiff(DateInterval.Year, TaroDay, Now)
                ' 月を求める
                Dim TaroMonth As Double
                TaroMonth = DateDiff(DateInterval.Month, TaroDay, Now) Mod 12

                '====== テスト花子の入社年月日 ======
                Dim HanakoDay As Date = "2002/4/1"
                ' 年を求める
                Dim HanakoYear As Integer
                HanakoYear = DateDiff(DateInterval.Year, HanakoDay, Now)
                ' 月を求める
                Dim HanakoMonth As Double
                HanakoMonth = DateDiff(DateInterval.Month, HanakoDay, Now) Mod 12

                '====== テスト次郎の入社年月日 ======
                Dim JiroDay As Date = "2003/4/1"
                ' 年を求める
                Dim JiroYear As Integer
                JiroYear = DateDiff(DateInterval.Year, JiroDay, Now)
                ' 月を求める
                Dim jiroMonth As Double
                jiroMonth = DateDiff(DateInterval.Month, JiroDay, Now) Mod 12

                'Nenji変数に格納
                'Dim Nenji As Integer
                'Nenji = TaroYear & Format(TaroYear, "年") & TaroMonth & Format(TaroMonth, "ヵ月") & HanakoYear & Format(HanakoYear, "年") & HanakoMonth & Format(HanakoMonth, "ヵ月") & JiroYear & Format(JiroYear, "年") & jiroMonth & Format(jiroMonth, "ヵ月")


                'row("年次") = TaroYear & Format(TaroYear, "年") & TaroMonth & Format(TaroMonth, "ヵ月").ToString() & Tab


                Dim strTSV As String

                strTSV = ""
                '社員コード
                strTSV = strTSV & row("社員コード").ToString() & Tab
                '社員氏名
                strTSV = strTSV & row("社員氏名").ToString() & Tab
                '社員英語
                strTSV = strTSV & row("社員英語").ToString() & Tab
                '部門コード
                strTSV = strTSV & row("部門コード").ToString() & Tab
                '部門名
                strTSV = strTSV & row("部門名").ToString() & Tab
                '入社年月日
                strTSV = strTSV & Nyusya.ToString("yy年mm月") & Tab
                '年次(太郎)
                strTSV = strTSV & TaroYear & Format(TaroYear, "年") & TaroMonth & Format(TaroMonth, "ヵ月").ToString() & Tab
                '年次(花子)
                strTSV = strTSV & HanakoYear & Format(HanakoYear, "年") & HanakoMonth & Format(HanakoMonth, "ヵ月").ToString() & Tab
                '年次(次郎)
                strTSV = strTSV & JiroYear & Format(JiroYear, "年") & jiroMonth & Format(jiroMonth, "ヵ月").ToString() & Tab
                '更新日時
                strTSV = strTSV & Kosin.ToString("yy年mm月dd日")

                Debug.Print("strTSVの値は" & strTSV)

                '改行する
                sw.WriteLine(strTSV)


            Next


            sw.Close()


            'コード全体のTry - Catch
        Catch ex As Exception

            MessageBox.Show(ex.Message, "エラー”)




        Finally

            '接続終了処理
            SyainTable.Dispose()
            sqlCom.Dispose()
            con.Close()
            con.Dispose()



        End Try


    End Sub


End Module
  • 0
  • 0
anonymous タイトルなし
PHP
<?php  
$dataFile ='index.txt';  
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if (isset($_POST['delete'])) {

$delete = $_POST['deleteNo'];
$delCon = file("index.txt");
for ($j = 0; $j < count($delCon) ; $j++){ 
$delData = explode("<>", $delCon[$j]);

if ($delData[0] == $delete) { 
array_splice($delCon, $j, 1);
file_put_contents($dataFile, implode("\n", $delCon));
}
}
} else {
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  

  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt. "\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  
}
}  
 ?>  

<!DOCTYPE html>
<html lang="ja">
  <head>
      <meta charset="UTF-8" />
      <title>簡易掲示板</title>
  </head>
  <body>
      <h1>簡易掲示板</h1>
      <form action="" method="post">
      <p> コメント: <input type="text" name="message"></p>
      <p>名前: <input type="text" name="user"></p>
      <input type="submit" value="投稿">
      </form>
      <!--削除用の入力フォーム-->
      <form action="" method="post"> 
      <p>削除対象番号<input type="text" name="delete"></p> 
      <input type="submit" name="deleteNo" value="削除"> 
     </form>
    
    <?php
    // ファイルの内容を配列に格納 
    $file_name = file("index.txt");

    for($i=0;$i<count($file_name);++$i){
    $file_names=explode("<>",$file_name[$i]);
    // 改行しながら値を表示 
    echo $file_names[0]."</br>";
    echo $file_names[1]."</br>";
    echo $file_names[2]."</br>";
    echo $file_names[3]."</br>";
    }
    ?>

  </body>
</html>
  • 0
  • 0
anonymous タイトルなし
PHP
yes()
  • 0
  • 0
anonymous タイトルなし
PHP
<?php
$input_lines = explode(' ', trim(fgets(STDIN)));
$pernum = $input_lines[0];
$linenum = $input_lines[1];
for ($i = 0; $i < $linenum; $i++) {
    $temp = explode(' ', trim(fgets(STDIN)));
    //$temp=explode(' ',explode(
    $temp1 = $temp[0];
    $temp2 = $temp[2];
    $temp3 = str_replace(array(' liar.', 'honest'), array('znz', 'zez'), $temp[5]);
    $ren[$i] = implode('', array($temp1, $temp3, $temp2));
}
//配列で重複している物を削除する 
$ren = array_unique($ren);
//キーが飛び飛びになっているので、キーを振り直す 
$ren = array_values($ren);
$linenum = count($ren);
//矛盾するかどうか? 
$mujun = false;
for ($i = 0; $i < $linenum; $i++) {
    $temp = explode('z', $ren[$i]);
    if ($temp[0] < $temp[2]) {
        $hoge = $temp[0];
        $temp[0] = $temp[2];
        $temp[2] = $hoge;
    }
    if ($temp[0] == $temp[2] && $temp[1] == 'n') {
        $mujun = true;
        break;
    }
    if (isset($record["$temp[0]" . ',' . "$temp[2]"])) {
        $mujun = true;
        break;
    } else {
        if ($temp[1] == 'e') {
            $record["$temp[0]" . ',' . "$temp[2]"] = 1;
        } else {
            $record["$temp[0]" . ',' . "$temp[2]"] = -1;
        }
    }
}
if ($mujun) {
    echo '-1';
} else {
    $res = $pernum - $linenum + 1;
    echo $res;
}
?>
  • 0
  • 0
anonymous タイトルなし
Python
print("aaaaaaaaaaaaaaaaaaa")
  • 0
  • 0
anonymous タイトルなし
PHP
<?php

try{
	//データベースへ接続
	$db = new PDO('msql:host=localhost;dbname=co_19_208_99sv_coco_com;charset=utf8','co-19-208.99sv-c','A8cjtYu3');

	//テーブルを作成する
	$sql = 'CREATE TABLE kadai2_test_table(
			number INT NOT NULL PRIMARY KEY,
			name VARCHAR(20) NOT NULL,
			message VARCHAR(100) NOT NULL,
			regist_timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
			)engine=innodb default charset=utf8';

	//SQL実行
	$res = $db->query($sql);

}catch(PDOException $e){
	echo "データベースに接続できません。".$e->getMessage();
	exit;
}

//接続を閉じる
$db = null;
	
?>
  • 0
  • 0
anonymous タイトルなし
Python
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets


def phi3(x):
    return x[:, 0] * x[:, 1] * np.pi


def XI(x):
    return (np.sin(x[:, 1]) * (np.sin(phi3(x))) ** 2 + np.sin(x[:, 0]) * (np.cos(phi3(x))) ** 2 + np.cos(
        x[:, 0]) * np.cos(x[:, 1]) * np.sin(phi3(x))) * np.sin(x[:, 0]) / 4


def YI(x):
    return (-np.sin(x[:, 1]) * np.cos(x[:, 0]) * (np.sin(phi3(x))) ** 2 - np.cos(x[:, 0]) * np.sin(x[:, 0]) * (
        np.cos(phi3(x))) ** 2 + ((np.sin(x[:, 0])) ** 2) * np.cos(x[:, 1]) * np.sin(phi3(x))) / 4


def ZI(x):
    return np.cos(x[:, 0]) * np.cos(phi3(x)) / 4


def IX(x):
    return (np.sin(x[:, 0]) * (np.sin(phi3(x))) ** 2 + np.sin(x[:, 1]) * (np.cos(phi3(x))) ** 2 + np.cos(
        x[:, 0]) * np.cos(x[:, 1]) * np.sin(phi3(x))) * np.sin(x[:, 1]) / 4


def XX(x):
    return (((np.sin(x[:, 1])) ** 2) * (np.sin(phi3(x))) ** 2 + np.cos(x[:, 0]) * np.cos(x[:, 1]) * np.sin(phi3(x)) * (
            np.sin(x[:, 0]) + np.sin(x[:, 1]))) / 4


def YX(x):
    return (-np.sin(x[:, 0]) * np.cos(x[:, 0]) * (np.sin(x[:, 1])) ** 2 + np.sin(phi3(x)) * np.cos(x[:, 1]) * (
            np.sin(x[:, 0]) * np.sin(x[:, 1]) - np.cos(x[:, 0]) * np.cos(x[:, 0]))) / 4


def ZX(x):
    return (-np.sin(x[:, 0]) * np.cos(x[:, 1]) * np.sin(phi3(x)) + np.cos(x[:, 0]) * (np.sin(x[:, 1])) ** 2 + np.sin(
        x[:, 1]) * np.cos(x[:, 1]) * np.sin(phi3(x))) * np.cos(phi3(x)) / 4


def IY(x):
    return (-np.sin(x[:, 0]) * np.cos(x[:, 1]) * (np.sin(phi3(x))) ** 2 - np.sin(x[:, 1]) * np.cos(x[:, 1]) * (
        np.cos(phi3(x))) ** 2 + ((np.sin(x[:, 1])) ** 2) * np.cos(x[:, 0]) * np.sin(phi3(x))) / 4


def XY(x):
    return (-np.sin(x[:, 1]) * np.cos(x[:, 1]) * (np.sin(x[:, 0])) ** 2 + np.sin(phi3(x)) * np.cos(x[:, 0]) * (
            np.sin(x[:, 0]) * np.sin(x[:, 1]) - np.cos(x[:, 1]) * np.cos(x[:, 1]))) / 4


def YY(x):
    return (np.sin(x[:, 0]) * np.cos(x[:, 0]) * np.sin(x[:, 1]) * np.cos(x[:, 1]) - np.sin(phi3(x)) * (
            np.sin(x[:, 0]) * (np.cos(x[:, 1])) ** 2 + np.sin(x[:, 1]) * (np.cos(x[:, 0])) ** 2)) / 4


def ZY(x):
    return (-np.sin(x[:, 0]) * np.sin(phi3(x)) * np.cos(phi3(x)) - np.cos(x[:, 1]) * np.cos(x[:, 0]) * np.cos(
        phi3(x)) + np.sin(x[:, 1]) * np.cos(phi3(x)) * np.sin(phi3(x))) * np.sin(x[:, 1]) / 4


def IZ(x):
    return np.cos(x[:, 1]) * np.cos(phi3(x)) / 4


def XZ(x):
    return (-np.sin(x[:, 1]) * np.cos(x[:, 0]) * np.sin(phi3(x)) + np.cos(x[:, 1]) * (np.sin(x[:, 0])) ** 2 + np.sin(
        x[:, 0]) * np.cos(x[:, 0]) * np.sin(phi3(x))) * np.cos(phi3(x)) / 4


def YZ(x):
    return (-np.sin(x[:, 1]) * np.sin(phi3(x)) * np.cos(phi3(x)) - np.cos(x[:, 1]) * np.cos(x[:, 0]) * np.cos(
        phi3(x)) + np.sin(x[:, 0]) * np.cos(phi3(x)) * np.sin(phi3(x))) * np.sin(x[:, 0]) / 4


def ZZ(x):
    return np.cos(x[:, 1]) * np.cos(x[:, 0]) / 4


# import some data to play with
iris = datasets.make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, factor=0.8)

x = iris[0]  # circle point data
W = iris[1]
Y = 2 * W - 1  # label data


def my_kernel(x1, x2):
    p1 = get_p_array(x1)
    p2 = get_p_array(x2)
    return np.dot(p1.T, p2)


def get_p_array(x):
    const = np.full(x.shape[0], 1 / 4)
    return np.array(
        [const, XI(x), YI(x), ZI(x), IX(x), XX(x), YX(x), ZX(x), IY(x), XY(x), YY(x), ZY(x), IZ(x), XZ(x), YZ(x),
         ZZ(x)])


h = .02  # step size in the mesh

# we create an instance of SVM and fit out data.
clf = svm.SVC(kernel=my_kernel)
clf.fit(x, Y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
plt.title('3-Class classification using Support Vector Machine with custom'
          ' kernel')
plt.axis('tight')
plt.show()
  • 0
  • 0
anonymous タイトルなし
Python
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
import math

def phi3(x):
    return x[0]*x[1]*math.pi
def XI(x):
    return (math.sin(x[1])*(math.sin(phi3(x)))**2+math.sin(x[0])*(math.cos(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x)))*math.sin(x[0])/4
def YI(x):
    return (-math.sin(x[1])*math.cos(x[0])*(math.sin(phi3(x)))**2-math.cos(x[0])*math.sin(x[0])*(math.cos(phi3(x)))**2+((math.sin(x[0]))**2)*math.cos(x[1])*math.sin(phi3(x)))/4
def ZI(x):
    return math.cos(x[0])*math.cos(phi3(x))/4
def IX(x):
    return (math.sin(x[0])*(math.sin(phi3(x)))**2+math.sin(x[1])*(math.cos(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x)))*math.sin(x[1])/4
def XX(x):
    return (((math.sin(x[1]))**2)*(math.sin(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x))*(math.sin(x[0])+math.sin(x[1])))/4
def YX(x):
    return (-math.sin(x[0])*math.cos(x[0])*(math.sin(x[1]))**2+math.sin(phi3(x))*math.cos(x[1])*(math.sin(x[0])*math.sin(x[1])-math.cos(x[0])*math.cos(x[0])))/4
def ZX(x):
    return (-math.sin(x[0])*math.cos(x[1])*math.sin(phi3(x))+math.cos(x[0])*(math.sin(x[1]))**2+math.sin(x[1])*math.cos(x[1])*math.sin(phi3(x)))*math.cos(phi3(x))/4
def IY(x):
    return (-math.sin(x[0])*math.cos(x[1])*(math.sin(phi3(x)))**2-math.sin(x[1])*math.cos(x[1])*(math.cos(phi3(x)))**2+((math.sin(x[1]))**2)*math.cos(x[0])*math.sin(phi3(x)))/4
def XY(x):
    return (-math.sin(x[1])*math.cos(x[1])*(math.sin(x[0]))**2+math.sin(phi3(x))*math.cos(x[0])*(math.sin(x[0])*math.sin(x[1])-math.cos(x[1])*math.cos(x[1])))/4
def YY(x):
    return (math.sin(x[0])*math.cos(x[0])*math.sin(x[1])*math.cos(x[1])-math.sin(phi3(x))*(math.sin(x[0])*(math.cos(x[1]))**2+math.sin(x[1])*(math.cos(x[0]))**2))/4
def ZY(x):
    return (-math.sin(x[0])*math.sin(phi3(x))*math.cos(phi3(x))-math.cos(x[1])*math.cos(x[0])*math.cos(phi3(x))+math.sin(x[1])*math.cos(phi3(x))*math.sin(phi3(x)))*math.sin(x[1])/4
def IZ(x):
    return math.cos(x[1])*math.cos(phi3(x))/4
def XZ(x):
    return (-math.sin(x[1])*math.cos(x[0])*math.sin(phi3(x))+math.cos(x[1])*(math.sin(x[0]))**2+math.sin(x[0])*math.cos(x[0])*math.sin(phi3(x)))*math.cos(phi3(x))/4
def YZ(x):
    return (-math.sin(x[1])*math.sin(phi3(x))*math.cos(phi3(x))-math.cos(x[1])*math.cos(x[0])*math.cos(phi3(x))+math.sin(x[0])*math.cos(phi3(x))*math.sin(phi3(x)))*math.sin(x[0])/4
def ZZ(x):
    return math.cos(x[1])*math.cos(x[0])/4

# import some data to play with
iris = datasets.make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, factor=0.8)

x = iris[0]
W = iris[1]
Y = W+W-1


def my_kernel(A, B):
    b = np.zeros((A.shape[0], B.shape[0]))
    for i in range(0,A.shape[0]):
        for j in range(0,B.shape[0]):
            x=A[i]
            y=B[j]
            PX=np.array([1/4,XI(x),YI(x),ZI(x),IX(x),XX(x),YX(x),ZX(x),IY(x),XY(x),YY(x),ZY(x),IZ(x),XZ(x),YZ(x),ZZ(x)])
            PY=np.array([1/4,XI(y),YI(y),ZI(y),IX(y),XX(y),YX(y),ZX(y),IY(y),XY(y),YY(y),ZY(y),IZ(y),XZ(y),YZ(y),ZZ(y)])
            b[i][j] += np.dot(PX,PY)
    return b

h = .02  # step size in the mesh

# we create an instance of SVM and fit out data.
clf = svm.SVC(kernel=my_kernel)
clf.fit(x, Y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
plt.title('3-Class classification using Support Vector Machine with custom'
          ' kernel')
plt.axis('tight')
plt.show()
  • 0
  • 0
anonymous タイトルなし
Python
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
import math

def phi3(x):
    return x[0]*x[1]*math.pi
def XI(x):
    return (math.sin(x[1])*(math.sin(phi3(x)))**2+math.sin(x[0])*(math.cos(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x)))*math.sin(x[0])/4
def YI(x):
    return (-math.sin(x[1])*math.cos(x[0])*(math.sin(phi3(x)))**2-math.cos(x[0])*math.sin(x[0])*(math.cos(phi3(x)))**2+((math.sin(x[0]))**2)*math.cos(x[1])*math.sin(phi3(x)))/4
def ZI(x):
    return math.cos(x[0])*math.cos(phi3(x))/4
def IX(x):
    return (math.sin(x[0])*(math.sin(phi3(x)))**2+math.sin(x[1])*(math.cos(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x)))*math.sin(x[1])/4
def XX(x):
    return (((math.sin(x[1]))**2)*(math.sin(phi3(x)))**2+math.cos(x[0])*math.cos(x[1])*math.sin(phi3(x))*(math.sin(x[0])+math.sin(x[1])))/4
def YX(x):
    return (-math.sin(x[0])*math.cos(x[0])*(math.sin(x[1]))**2+math.sin(phi3(x))*math.cos(x[1])*(math.sin(x[0])*math.sin(x[1])-math.cos(x[0])*math.cos(x[0])))/4
def ZX(x):
    return (-math.sin(x[0])*math.cos(x[1])*math.sin(phi3(x))+math.cos(x[0])*(math.sin(x[1]))**2+math.sin(x[1])*math.cos(x[1])*math.sin(phi3(x)))*math.cos(phi3(x))/4
def IY(x):
    return (-math.sin(x[0])*math.cos(x[1])*(math.sin(phi3(x)))**2-math.sin(x[1])*math.cos(x[1])*(math.cos(phi3(x)))**2+((math.sin(x[1]))**2)*math.cos(x[0])*math.sin(phi3(x)))/4
def XY(x):
    return (-math.sin(x[1])*math.cos(x[1])*(math.sin(x[0]))**2+math.sin(phi3(x))*math.cos(x[0])*(math.sin(x[0])*math.sin(x[1])-math.cos(x[1])*math.cos(x[1])))/4
def YY(x):
    return (math.sin(x[0])*math.cos(x[0])*math.sin(x[1])*math.cos(x[1])-math.sin(phi3(x))*(math.sin(x[0])*(math.cos(x[1]))**2+math.sin(x[1])*(math.cos(x[0]))**2))/4
def ZY(x):
    return (-math.sin(x[0])*math.sin(phi3(x))*math.cos(phi3(x))-math.cos(x[1])*math.cos(x[0])*math.cos(phi3(x))+math.sin(x[1])*math.cos(phi3(x))*math.sin(phi3(x)))*math.sin(x[1])/4
def IZ(x):
    return math.cos(x[1])*math.cos(phi3(x))/4
def XZ(x):
    return (-math.sin(x[1])*math.cos(x[0])*math.sin(phi3(x))+math.cos(x[1])*(math.sin(x[0]))**2+math.sin(x[0])*math.cos(x[0])*math.sin(phi3(x)))*math.cos(phi3(x))/4
def YZ(x):
    return (-math.sin(x[1])*math.sin(phi3(x))*math.cos(phi3(x))-math.cos(x[1])*math.cos(x[0])*math.cos(phi3(x))+math.sin(x[0])*math.cos(phi3(x))*math.sin(phi3(x)))*math.sin(x[0])/4
def ZZ(x):
    return math.cos(x[1])*math.cos(x[0])/4

# import some data to play with
iris = datasets.make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, factor=0.8)

x = iris[0]
W = iris[1]
Y = W+W-1


def my_kernel(A, B):
    b = np.zeros((Y.shape[0], Y.shape[0]))
    for i in range(0,Y.shape[0]):
        for j in range(0,Y.shape[0]):
            x=A[i]
            y=B[j]
            PX=np.array([1/4,XI(x),YI(x),ZI(x),IX(x),XX(x),YX(x),ZX(x),IY(x),XY(x),YY(x),ZY(x),IZ(x),XZ(x),YZ(x),ZZ(x)])
            PY=np.array([1/4,XI(y),YI(y),ZI(y),IX(y),XX(y),YX(y),ZX(y),IY(y),XY(y),YY(y),ZY(y),IZ(y),XZ(y),YZ(y),ZZ(y)])
            b[i][j] += np.dot(PX,PY)
    return b

h = .02  # step size in the mesh

# we create an instance of SVM and fit out data.
clf = svm.SVC(kernel=my_kernel)
clf.fit(x, Y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
plt.title('3-Class classification using Support Vector Machine with custom'
          ' kernel')
plt.axis('tight')
plt.show()
  • 0
  • 0